The latest version of ggplot2 has removed the order aesthetic, which one could previously use to specify the stacking order of bar charts. In this example, the first chart has the legend ordered as a > b > c.
df <- data.frame(date = rep(seq(as.Date("2015-11-02"),
as.Date("2015-11-03"), 1), each = 3),
country = rep(c("a", "b", "c"), 2),
value = c(10, 2, 4, 3, 2, 5), stringsAsFactors = FALSE)
ggplot(df, aes(x = date, y = value, fill = country)) +
geom_bar(stat = "identity") +
scale_x_date(labels = date_format("%Y-%m-%d"))
I then reorder the country
variable to be in the order according to the last date (i.e. c > a > b). I would now want c to be at the bottom, both in the stack and in the legend. However, only the colors and legend switch around, not the stacking order.
temp <- subset(df, date == max(df$date))
level_order <- temp[order(temp$value, decreasing = TRUE), "country"]
df$country <- factor(df$country, levels = level_order)
ggplot(df, aes(x = date, y = value, fill = country)) +
geom_bar(stat = "identity") +
scale_x_date(labels = date_format("%Y-%m-%d"))
In earlier version of ggplot2 one could fix this with aes(order = country). How does one do it now that order
is gone?
Update:
The deprecation of the order
aesthetic was announced in the news for ggplot2 version 1.10. The documentation for aes_group_order refers to version 0.9.3.1.
As discussed in one of the answers below, the stacking order appears to depend on where it appears in the data frame. Accordingly, on can change the stacking order by sorting the data frame before plotting. This seems like very strange behavior, and it leads to different stacking order between bars.