Plotting error bars with position = "dodge"
has caused me many headaches lately... Curiously, dodging them with the aesthetics shape
or fill
(which should not apply for error bars) seem to work well. However, dodging with aesthetics group
places the bars in unexpected positions. I was wondering if this might be a ggplot2 bug.
I like placing custom error bars behind bar plots or boxplots. Sometimes I give special colors to different elements of my plots. For this reason, I often include aes()
not in the ggplot()
function, but in the geoms or stats.
Here is an example of "well placed" error bars:
library(ggplot2)
library(dplyr)
ToothGrowth %>%
mutate(dose = factor(dose)) %>%
ggplot(aes(dose, len)) +
stat_boxplot(aes(fill = supp), geom = "errorbar", position = "dodge") +
geom_boxplot(aes(fill = supp), position = "dodge", coef = 0)
This produces the warning Warning: Ignoring unknown aesthetics: fill
. Using aes(shape = supp)
prints the same plot.
I would expect that same plot, but no warnings by exchanging fill/shape with "group" (aes(group = supp)
). This produces no warnings, but a very unexpected result:
ToothGrowth %>%
mutate(dose = factor(dose)) %>%
ggplot(aes(dose, len)) +
stat_boxplot(aes(group = supp), geom = "errorbar", position = "dodge") +
geom_boxplot(aes(fill = supp), position = "dodge", coef = 0)
Would someone have an explanation for this behavior? Shouldn't grouping with aes(group = ...)
and aes(fill = ...)
behave similarly on the dodge position?