Is there a way to control which element is plotted in front of the other if one uses dodged bar charts.
ggplot(mtcars, aes(x=factor(cyl), fill=factor(vs))) +
Your control here is limited. Using factor levels we can control i) the fill
color ordering and ii) the ordering of position_dodge
using group
.
Here are the four options:
p1 <- ggplot(mtcars, aes(x = factor(cyl), fill = factor(vs, 0:1), group = factor(vs, 0:1))) +
geom_bar(position = position_dodge(width = - 0.5))
p2 <- ggplot(mtcars, aes(x = factor(cyl), fill = factor(vs, 0:1), group = factor(vs, 1:0))) +
geom_bar(position = position_dodge(width = - 0.5))
p3 <- ggplot(mtcars, aes(x = factor(cyl), fill = factor(vs, 1:0), group = factor(vs, 0:1))) +
geom_bar(position = position_dodge(width = - 0.5))
p4 <- ggplot(mtcars, aes(x = factor(cyl), fill = factor(vs, 1:0), group = factor(vs, 1:0))) +
geom_bar(position = position_dodge(width = - 0.5))
library(cowplot)
plot_grid(p1, p2, p3, p4, align = 'hv')
So it seems only the dodging order is important. In the dev version at least, the right bar is always plotted in front of the left bar.