2
votes

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: enter image description here

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
Add excitation as a level to your dampingtime factor in whatever order you want. You don't need to have observations of a level to include it in the levels, e.g. factor(c("a", "b"), levels = c("z", "a", "b")).Gregor Thomas
Thanks, but it didn't work. See my edited answerdenis

1 Answers

1
votes

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"))