How do you order the fill-colours within ggplot2 geom_bar

Starting in ggplot2_2.0.0, the order aesthetic is no longer available. To get a graph with the stacks ordered by fill color, you can simply order the dataset by the grouping variable you want to order by.

I often use arrange from dplyr for this. Here I’m ordering the dataset by the fill factor within the ggplot call rather than creating an ordered dataset but either will work fine.

library(dplyr)

ggplot(arrange(data, gclass), aes(mon, NG, fill = gclass)) +
    geom_bar(stat = "identity")

This is easily done in base R, of course, using the classic order with the extract brackets:

ggplot(data[order(data$gclass), ], aes(mon, NG, fill = gclass)) +
    geom_bar(stat = "identity")

With the resulting plot in both cases now in the desired order:
enter image description here

ggplot2_2.2.0 update

In ggplot_2.2.0, fill order is based on the order of the factor levels. The default order will plot the first level at the top of the stack instead of the bottom.

If you want the first level at the bottom of the stack you can use reverse = TRUE in position_stack. Note you can also use geom_col as shortcut for geom_bar(stat = "identity").

ggplot(data, aes(mon, NG, fill = gclass)) +
    geom_col(position = position_stack(reverse = TRUE))

Leave a Comment