Include space for missing factor level used in fill aesthetics in geom_boxplot

Here is a solution, which is based on creating fake data:

Firstly, a new row is added to the data frame. It contains a data point for the non-existing combination of factor levels (Mar and A). The value of Height has to be outside the range of the real Height data.

Data2 <- rbind(Data, data.frame(Month = "Mar", Site = "A", Height = 5))

Then, the plot can be generated. Since the fake data should not be visible, the y axis limits have to be modified with coord_cartesian and the range of the original Height data.

library(ggplot2)
ggplot(Data2, aes(Site, Height)) +
  geom_boxplot(aes(fill = Month)) +
  coord_cartesian(ylim = range(Data$Height) + c(-.25, .25))

enter image description here

Leave a Comment