[R] Change the legend order by order function

S Ellison S@E|||@on @end|ng |rom LGCGroup@com
Wed May 23 13:29:01 CEST 2018

> -----Original Message-----
> From: R-help [mailto:r-help-bounces using r-project.org] 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}}

More information about the R-help mailing list