Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flip ordering of legend without altering ordering in plot

Tags:

I have found that when adding coord_flip() to certain plots using ggplot2 that the order of values in the legend no longer lines up with the order of values in the plot.

For example:

dTbl = data.frame(x=c(1,2,3,4,5,6,7,8),                   y=c('a','a','b','b','a','a','b','b'),                   z=c('q','q','q','q','r','r','r','r'))  print(ggplot(dTbl, aes(x=factor(y),y=x, fill=z)) +       geom_bar(position=position_dodge(), stat='identity') +       coord_flip() +       theme(legend.position='top', legend.direction='vertical')) 

enter image description here

I would like the 'q' and 'r' in the legend to be reversed without changing the order of 'q' and 'r' in the plot.

scale.x.reverse() looked promising, but it doesn't seem to work within factors (as is the case for this bar plot).

like image 417
Clayton Stanley Avatar asked Mar 19 '14 20:03

Clayton Stanley


People also ask

How do you reverse the order of a legend in Powerpoint?

In Design mode, right-click the chart legend you want to edit. Click Format Chart Legend. Check Reverse legend order.

How do I reorder the legend in an Excel chart?

Under Chart Tools, on the Design tab, in the Data group, click Select Data. In the Select Data Source dialog box, in the Legend Entries (Series) box, click the data series that you want to change the order of. Click the Move Up or Move Down arrows to move the data series to the position that you want.


1 Answers

You're looking for guides:

ggplot(dTbl, aes(x=factor(y),y=x, fill=z)) +       geom_bar(position=position_dodge(), stat='identity') +       coord_flip() +       theme(legend.position='top', legend.direction='vertical') +        guides(fill = guide_legend(reverse = TRUE)) 

I was reminded in chat by Brian that there is a more general way to do this for arbitrary orderings, by setting the breaks argument:

ggplot(dTbl, aes(x=factor(y),y=x, fill=z)) +       geom_bar(position=position_dodge(), stat='identity') +       coord_flip() +       theme(legend.position='top', legend.direction='vertical') +        scale_fill_discrete(breaks = c("r","q")) 
like image 181
joran Avatar answered Sep 17 '22 14:09

joran