You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Document behavior of fill order in geom_bar when stat = "identity" #1593
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 either position = "stack" or position = "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")
Note that this is due to the removal of the order aesthetic in 2.0.0, which could be used previously and has now lead to ambitious StackOverflow answers.
#1693 puts geom_bar in line with the other geoms, that is, reordering factor levels now reorder stacking order. Is there still merit in adding the order aesthetic? or should we close once #1693 has been merged?
Activity
minimaxir commentedon Mar 27, 2016
Note that this is due to the removal of the
orderaesthetic in 2.0.0, which could be used previously and has now lead to ambitious StackOverflow answers.hadley commentedon Jul 28, 2016
It might be worth bringing
orderback, and making it work in more cases (along with unit tests and documentation)thomasp85 commentedon Aug 3, 2016
#1693 puts
geom_barin line with the other geoms, that is, reordering factor levels now reorder stacking order. Is there still merit in adding theorderaesthetic? or should we close once #1693 has been merged?hadley commentedon Aug 3, 2016
I think we can probably close
thomasp85 commentedon Aug 12, 2016
Fixed in #1693