ggplot2 multiple sub groups of a bar chart

This may be a start.

dodge <- position_dodge(width = 0.9)

ggplot(df, aes(x = interaction(Variety, Trt), y = yield, fill = factor(geno))) +
  geom_bar(stat = "identity", position = position_dodge()) +
  geom_errorbar(aes(ymax = yield + SE, ymin = yield - SE), position = dodge, width = 0.2)

enter image description here

Update: labelling of x axis
I have added:
coord_cartesian, to set limits of y axis, mainly the lower limit to avoid the default expansion of the axis.
annotate, to add the desired labels. I have hard-coded the x positions, which I find OK in this fairly simple example.
theme_classic, to remove the gray background and the grid.
theme, increase lower plot margin to have room for the two-row label, remove default labels.
Last set of code: Because the text is added below the x-axis, it ‘disappears’ outside the plot area, and we need to remove the ‘clipping’. That’s it!

library(grid)

g1 <- ggplot(data = df, aes(x = interaction(Variety, Trt), y = yield, fill = factor(geno))) +
  geom_bar(stat = "identity", position = position_dodge()) +
  geom_errorbar(aes(ymax = yield + SE, ymin = yield - SE), position = dodge, width = 0.2) +
  coord_cartesian(ylim = c(0, 7500)) +
  annotate("text", x = 1:4, y = - 400,
           label = rep(c("Variety 1", "Variety 2"), 2)) +
  annotate("text", c(1.5, 3.5), y = - 800, label = c("Irrigated", "Dry")) +
  theme_classic() +
  theme(plot.margin = unit(c(1, 1, 4, 1), "lines"),
       axis.title.x = element_blank(),
       axis.text.x = element_blank())

# remove clipping of x axis labels
g2 <- ggplot_gtable(ggplot_build(g1))
g2$layout$clip[g2$layout$name == "panel"] <- "off"
grid.draw(g2)

enter image description here

Leave a Comment