[R] Change the legend order by order function
Jeff Newmiller
jdnewm|| @end|ng |rom dcn@d@v|@@c@@u@
Wed May 23 12:55:44 CEST 2018
There are two key concepts you seem to be unaware of regarding ggplot: 1) you really need to put your data in long format to work with multiple curves, and 2) the column containing the names of the curves should be a factor with levels in the order you wish them to be presented in the legend (bottom to top). I am not in a position at the moment to give you a full reprex, but Google can probably help you find lots of examples... try keywords factor long ggplot.
Regarding using order to do this, the answer is likely "yes" but your existing example order seems easier to do with an explicit listing of labels in sequence... I cannot fathom why you think name_b, name_c, name_a is a natural result of using the order function that people will want to see. Either be explicit or use an alphabetic order, either way does not need the order function.
On May 23, 2018 10:27:14 AM GMT+02:00, John <miaojpm using gmail.com> wrote:
>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
--
Sent from my phone. Please excuse my brevity.
More information about the R-help
mailing list