Reverse stacked bar order

The release notes of ggplot2 version 2.2.0 on Stacking bars suggest:

If you want to stack in the opposite order, try forcats::fct_rev()

library(ggplot2)   # version 2.2.1 used    
plot_df <- data.frame(group = rep(1:4, 6),
                      levels = factor(c(rep(1:5, each = 4), rep(1, 4))))
ggplot(plot_df, aes(group, fill = forcats::fct_rev(levels))) + 
  geom_bar(position = "fill")

Reverse levels

This is the original plot:

ggplot(plot_df, aes(group, fill = levels)) + 
  geom_bar(position = "fill")

Original plot

Or, using position_fill(reverse = TRUE) as suggested by alistaire in his comment:

ggplot(plot_df, aes(group, fill = levels)) + 
  geom_bar(position = position_fill(reverse = TRUE))

enter image description here

Note that the levels (colors) in the legend is not in the same order as in the stacked bars.

Leave a Comment