10
votes

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.

1

1 Answers

13
votes

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