Reorder the legend without changing the order of the points in the plot

I keep running into this problem in ggplot2, maybe someone can help me.

I have a graph where the order of the variables in the legend is in the reverse order as they appear on the graph.

For example:

df=data.frame( mean=runif(9,2,3), Cat1=rep(c("A","B","C"),3), Cat2=rep(c("X","Y","Z"),each=3)) dodge=position_dodge(width=1) ggplot(df,aes(x=Cat1,y=mean,color=Cat2))+ geom_point(aes(shape=Cat2),size=4,position=dodge)+ scale_color_manual(values=c("red","blue","black"))+ scale_shape_manual(values=c(16:19))+ coord_flip() 

gives:

example

Thus, the points are displayed on the graph as Cat2 = Z, Y, then X (black diamonds, blue triangle, red circle), but in the legend they are displayed as Cat2 = X, Y, then Z (red circle, blue triangle, black diamond )

How can I change the order of a legend without changing the points on the chart? Reordering the factor creates the opposite task (points on the graph change to the opposite).

Thanks!

+8
r ggplot2 legend
source share
2 answers

To expose Hadley's comment, we would do something like this:

 ggplot(df,aes(x=Cat1,y=mean,color=Cat2))+ geom_point(aes(shape=Cat2),size=4,position=dodge)+ scale_color_manual(values=c("red","blue","black"),breaks = c('Z','Y','X'))+ scale_shape_manual(values=c(16:19),breaks = c('Z','Y','X'))+ coord_flip() 

enter image description here

Please note that we had to set the gaps in both scales. If we did only one, they would not correspond, and ggplot would divide them into two legends, and not to combine them.

+3
source share

As far as I understand what you want to achieve, this simple manipulation does the trick for me:

  • identify Cat2 as a factor (with levels in the appropriate order) and
  • arrange the order of colors and shapes according to the order of levels (in scale_manual commands)

Here is the code for this:

 library(ggplot2) df=data.frame( mean=runif(9,2,3), Cat1=rep(c("A","B","C"),3), Cat2=factor(rep(c("X","Y","Z"),each=3), levels=c('Z', 'Y', 'X'))) dodge=position_dodge(width=1) ggplot(df,aes(x=Cat1,y=mean,color=Cat2))+ geom_point(aes(shape=Cat2),size=4,position=dodge)+ scale_color_manual(values=c("black","blue","red"))+ scale_shape_manual(values=c(18:16))+ coord_flip() 
0
source share

All Articles