Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse stacking order without affecting legend order in ggplot2 bar charts

Tags:

r

ggplot2

How do I change the stacking order in a bar chart in ggplot2? shows how to reverse the stacking order, but the solution also changes the order shown in the legend. I'd like to change the stacking order without affecting the legend order, such that the top class in the legend is also the top class in stacking.

library(ggplot2)
data(mtcars)
ggplot(mtcars, aes(factor(cyl), fill=gear)) + geom_bar()

Original column chart using <code>ggplot2::ggplot</code>

To reverse the stacking order, reverse the factor levels. This also reverses the legend order.

mtcars$gear <- factor(mtcars$gear)  # First make factor with default levels
mtcars$gear <- factor(mtcars$gear, levels=rev(levels(mtcars$gear)))
ggplot(mtcars, aes(factor(cyl), fill=gear)) + geom_bar()

Reversed column chart

How to reverse legend (labels and color) so high value starts downstairs? suggests guide_legend(reverse=T) but isn't easily reproducible and doesn't pertain to stacked bar charts.

like image 375
Max Ghenis Avatar asked Jul 17 '16 21:07

Max Ghenis


People also ask

How do I reverse the legend order in ggplot2?

To Reverse the order of Legend, we have to add guides() and guide_legend() functions to the geom_point() function. Inside guides() function, we take the parameter color, which will call guide_legend() guide function as value.

How do I rearrange bars in ggplot2?

Reordering in ggplot is done using theme() function. Within this, we use axis. text. x with the appropriate value to re-order accordingly.


1 Answers

You can reverse the legend order using scale_fill_discrete:

ggplot(mtcars, aes(factor(cyl), fill=gear)) + geom_bar() + 
    scale_fill_discrete(guide=guide_legend(reverse=T))

Plot of reversed legend order

like image 156
Max Ghenis Avatar answered Oct 04 '22 00:10

Max Ghenis