Change the legend order by order function

classic Classic list List threaded Threaded
4 messages Options
Reply | Threaded
Open this post in threaded view
|

Change the legend order by order function

miao
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]]

______________________________________________
[hidden email] mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Reply | Threaded
Open this post in threaded view
|

Re: Change the legend order by order function

Jeff Newmiller
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 <[hidden email]> 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.

______________________________________________
[hidden email] mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Reply | Threaded
Open this post in threaded view
|

Re: Change the legend order by order function

PIKAL Petr
Hi

Which is actually answer the OP already got.

> library(ggplot2)
> df<-data.frame(x1=c(1,2), y1=c(3,4),z1=c(5,6),w1=c(7,8))
> library(reshape2)
> dfm<-melt(df)
No id variables; using all as measure variables
> dfm$variable<-factor(dfm$variable, levels=levels(dfm$variable)[c(2,1,3,4)])
> p2<-ggplot(dfm, aes(x=rep(1:2,4), y=value))
> p2+geom_line(aes(linetype=variable))+
+ scale_linetype_manual(values=c("solid", "dashed", "dotted", "blank"),
+ labels=c("name_b","name_a","name_c", "other"))
>
Cheers
Petr

Tento e-mail a jakékoliv k němu připojené dokumenty jsou důvěrné a podléhají tomuto právně závaznému prohlášení o vyloučení odpovědnosti: https://www.precheza.cz/01-dovetek/ | This email and any documents attached to it may be confidential and are subject to the legally binding disclaimer: https://www.precheza.cz/en/01-disclaimer/

> -----Original Message-----
> From: R-help [mailto:[hidden email]] On Behalf Of Jeff
> Newmiller
> Sent: Wednesday, May 23, 2018 12:56 PM
> To: John <[hidden email]>; r-help <[hidden email]>; David
> Winsemius <[hidden email]>; Rui Barradas <[hidden email]>
> Subject: Re: [R] Change the legend order by order function
>
> 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 <[hidden email]>
> 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.
>
> ______________________________________________
> [hidden email] mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

________________________________
Tento e-mail a jakékoliv k němu připojené dokumenty jsou důvěrné a jsou určeny pouze jeho adresátům.
Jestliže jste obdržel(a) tento e-mail omylem, informujte laskavě neprodleně jeho odesílatele. Obsah tohoto emailu i s přílohami a jeho kopie vymažte ze svého systému.
Nejste-li zamýšleným adresátem tohoto emailu, nejste oprávněni tento email jakkoliv užívat, rozšiřovat, kopírovat či zveřejňovat.
Odesílatel e-mailu neodpovídá za eventuální škodu způsobenou modifikacemi či zpožděním přenosu e-mailu.

V případě, že je tento e-mail součástí obchodního jednání:
- vyhrazuje si odesílatel právo ukončit kdykoliv jednání o uzavření smlouvy, a to z jakéhokoliv důvodu i bez uvedení důvodu.
- a obsahuje-li nabídku, je adresát oprávněn nabídku bezodkladně přijmout; Odesílatel tohoto e-mailu (nabídky) vylučuje přijetí nabídky ze strany příjemce s dodatkem či odchylkou.
- trvá odesílatel na tom, že příslušná smlouva je uzavřena teprve výslovným dosažením shody na všech jejích náležitostech.
- odesílatel tohoto emailu informuje, že není oprávněn uzavírat za společnost žádné smlouvy s výjimkou případů, kdy k tomu byl písemně zmocněn nebo písemně pověřen a takové pověření nebo plná moc byly adresátovi tohoto emailu případně osobě, kterou adresát zastupuje, předloženy nebo jejich existence je adresátovi či osobě jím zastoupené známá.

This e-mail and any documents attached to it may be confidential and are intended only for its intended recipients.
If you received this e-mail by mistake, please immediately inform its sender. Delete the contents of this e-mail with all attachments and its copies from your system.
If you are not the intended recipient of this e-mail, you are not authorized to use, disseminate, copy or disclose this e-mail in any manner.
The sender of this e-mail shall not be liable for any possible damage caused by modifications of the e-mail or by delay with transfer of the email.

In case that this e-mail forms part of business dealings:
- the sender reserves the right to end negotiations about entering into a contract in any time, for any reason, and without stating any reasoning.
- if the e-mail contains an offer, the recipient is entitled to immediately accept such offer; The sender of this e-mail (offer) excludes any acceptance of the offer on the part of the recipient containing any amendment or variation.
- the sender insists on that the respective contract is concluded only upon an express mutual agreement on all its aspects.
- the sender of this e-mail informs that he/she is not authorized to enter into any contracts on behalf of the company except for cases in which he/she is expressly authorized to do so in writing, and such authorization or power of attorney is submitted to the recipient or the person represented by the recipient, or the existence of such authorization is known to the recipient of the person represented by the recipient.

______________________________________________
[hidden email] mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Reply | Threaded
Open this post in threaded view
|

Re: Change the legend order by order function

S Ellison-2
In reply to this post by Jeff Newmiller


> -----Original Message-----
> From: R-help [mailto:[hidden email]] On Behalf Of Jeff Newmiller
> Subject: Re: [R] Change the legend order by order function
>
> [snip]
>
> 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.

Things like 'high', 'med', 'low' also often need some care to avoid an inappropriate alphabetical ordering.

ggplot (like many base graphics) will typically sort and display by level order in a factor, not alphabetically.

So the key is to set the factor levels in the appropriate order in the first place. If you define the factor level order explicitly on creating the factor, as in
gp <- factor(<a vector>,  levels=c("name_b", "name_c", "name_a"))
#or, for a more obviously likely example
lmh <- factor(sample(c("High", "Medium", "Low"), 30, replace=T),  levels=c("Low", "Medium", "High"))

ggplot will then display legends etc in the defined and now appropriate factor level order by default.

S Ellison


*******************************************************************
This email and any attachments are confidential. Any use...{{dropped:8}}

______________________________________________
[hidden email] mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.