Reputation: 15793
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()
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()
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.
Upvotes: 12
Views: 6693
Reputation: 15793
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))
Upvotes: 18