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 ?
excitation
as a level to yourdampingtime
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