Description
One of the most commonly asked questions about ggplot is how to order categorical aesthetics, and the answer is has traditionally been to specify the order in the factor levels.
With the most recent version this has changed for (at least) the case of geom_bar
when stat = "identity"
and either position = "stack"
or position = "fill"
. Instead, to ensure that the filled segments in a stacked/filled bar plot are in a specified order we must now have the data frame sorted in the desired order.
This should probably at least be documented in the Details section of ?geom_bar
, with a brief note along the lines of:
To adjust the order of the levels of the fill aesthetic when using
stat = "identity"
and eitherposition = "stack"
orposition = "fill"
the data itself must be arranged in the desired order. Adjusting the order of the factor levels no longer has any effect in these cases.
Here's a very minimal example demonstrating this behavior:
library(ggplot2)
library(dplyr)
dat <- data.frame(x = rep(1:2,each = 3),
y = 1:6,
f = rep(letters[1:3],times = 2))
dat$f1 <- with(dat,factor(f,levels = c('c','b','a')))
dat
#Original
ggplot() +
geom_bar(data = dat,
aes(x = factor(x),y = y,fill = f),
stat = "identity",
position = "stack")
#Fill colors have changed, but not order of segments
ggplot() +
geom_bar(data = dat,
aes(x = factor(x),y = y,fill = f1),
stat = "identity",
position = "stack")
#Reorder data frame
dat <- arrange(dat,x,desc(f))
dat
#Now the order changed
ggplot() +
geom_bar(data = dat,
aes(x = factor(x),y = y,fill = f),
stat = "identity",
position = "stack")
The same behavior occurs when position = "fill"
.