How to change the order of elements in a legend?

I am trying to change the display order of legend elements. I spent about an hour on this, with no results.

Here's an installation example:

library(ggplot2) set.seed(0) d <- data.frame(x = runif(3), y = runif(3), a = c('1', '3', '10')) 

And here is one of the many things I've tried:

 ggplot(d, aes(x = x, y = y)) + geom_point(size=7, aes(color = a, order = as.numeric(a))) 

enter image description here

(My naive hope, of course, was that the elements of the legend would be shown in numerical order: 1, 3, 10.)

+5
source share
2 answers

ggplot usually orders your factor values ​​according to factor levels() . It’s best to make sure that this is the order you need, otherwise you will be fighting with a lot of functions in R, but you can manually change this by manipulating the color scale:

 ggplot(d, aes(x = x, y = y)) + geom_point(size=7, aes(color = a)) + scale_color_discrete(breaks=c("1","3","10")) 
+8
source

The order of legend labels can be manipulated by reordering and changing the values ​​in column a by a factor: d$a <- factor(d$a, levels = d$a)

So your code will look like this:

 library(ggplot2) set.seed(0) d <- data.frame(x = runif(3), y = runif(3), a = c('1', '3', '10')) d$a <- factor(d$a, levels = d$a) ggplot(d, aes(x = x, y = y)) + geom_point(size=7, aes(color = a)) 

And conclusion enter image description here

Note that now in the legend: 1 red, 3 - green, and 10 - blue.

+2
source

All Articles