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.
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.
Reordering in ggplot is done using theme() function. Within this, we use axis. text. x with the appropriate value to re-order accordingly.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With