[R] Change the legend order by order function
John
mi@ojpm @ending from gm@il@com
Wed May 23 10:27:14 CEST 2018
Hi,
I'd like to graph three lines on ggplot2 and I intend the lines to be
"solid", "dashed", and "dotted". The legend names are "name_b", "name_c",
"name_a". I'd like to legend to present in the order: the "name_b" at the
top, and "name_a" at the bottom.
Could it be done by order function or its inverse?
Thanks,
##### source code
library(ggplot2)
od<-order(c("name_b", "name_c", "name_a"))
df<-data.frame(x1=c(1,2), y1=c(3,4),z1=c(5,6),w1=c(7,8))
p1<-ggplot(df, aes(x=1:2, y=x1))+
geom_line(aes(linetype="name_b"))+
geom_line(aes(x=1:2, y=y1, linetype="name_c"), df)+
geom_line(aes(x=1:2, y=z1, linetype="name_a"), df)+
scale_linetype_manual(name="", values=c("solid","dashed", "dotted")[(od)],
labels=c("name_b","name_c","name_a"))
#### supplement
> od
[1] 3 1 2
> order(od)
[1] 2 3 1
[[alternative HTML version deleted]]
More information about the R-help
mailing list