ggplot legend: change order of the automatic legend

大憨熊 提交于 2021-02-10 08:40:17

问题


I am struggling with the legend order in ggplot when there are several group of plots. Here is an example:

library(ggplot2)
library(data.table)
data <- data.table(time = rep(1:50,4),dampingtime = rep(c(4,8,12,16),each = 50),
                   excitation = rep(c(rep(0,10),rep(1,10),rep(0,30)),4))
data[,signal := time + .GRP, by = dampingtime]
data[,dampingtime := as.factor(dampingtime)]

Here I have

> levels(data$dampingtime)
[1] "4"  "8"  "12" "16"

which I did accordingly to ggplot legends - change labels, order and title, and I do get the proper legend order when I do

ggplot(data = data) +
geom_point(aes(time,signal,color = dampingtime)) 

my problem is that I want to add the excitation column with an entry to the legend, so I do:

ggplot(data = data) +
geom_line(aes(time,excitation,color = "excitation")) +
geom_point(aes(time,signal,color = dampingtime)) 

In this case, the order is wrong for the number:

following Greor comment, I added excitation to the factor levels

data[,dampingtime := factor(dampingtime,levels = c(levels(dampingtime),"excitation"))]
levels(data$dampingtime)
[1] "4"          "8"          "12"         "16"         "excitation"

but i get exactly the same problem. How should I do to get the proper order ?


回答1:


You can get the order you want by specifying scale_colour_discrete

ggplot(data = data) +
 geom_line(aes(time,excitation,color = "excitation")) +
 geom_point(aes(time,signal,color = dampingtime)) +
 scale_colour_discrete(breaks=c("4","8","12","16","excitation"), labels=c(4,8,12,16,"excitation"))


来源:https://stackoverflow.com/questions/49900104/ggplot-legend-change-order-of-the-automatic-legend

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!