Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reorder the items in a legend?

Tags:

I'm trying to change the order in which legend items appear. I've spent about an hour at this, with no results.

Here's an example setup:

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

And here's 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 legend items would be shown in the numeric order: 1, 3, 10.)

like image 391
kjo Avatar asked Jul 27 '16 17:07

kjo


People also ask

How do you rearrange chart legends?

Click the chart, and then click the Chart Layout tab. To change the position of the legend, under Labels, click Legend, and then click the legend position that you want. To change the format of the legend, under Labels, click Legend, click Legend Options, and then make the format changes that you want.

How do I change the order of items in legend ggplot2?

You can use the following syntax to change the order of the items in a ggplot2 legend: scale_fill_discrete(breaks=c('item4', 'item2', 'item1', 'item3', ...)


2 Answers

ggplot will usually order your factor values according to the levels() of the factor. You are best of making sure that is the order you want otherwise you will be fighting with a lot of function 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")) 
like image 133
MrFlick Avatar answered Sep 23 '22 14:09

MrFlick


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

So your code would 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 the ouptut enter image description here

Note, than now in legend: 1 is red, 3 is green and 10 is blue color

like image 45
Miha Avatar answered Sep 24 '22 14:09

Miha