There are a few ways to do this:
1. Using middle
The easiest is to simply call:
plot <- ggplot(data = df, aes(y = dust, x = wind)) +
geom_boxplot(aes(middle = mean(dust))
2. Using fatten = NULL
You can also take advantage of the fatten
parameter in geom_boxplot()
. This controls the thickness of the median line. If we set it to NULL
, then it will not plot a median line, and we can insert a line for the mean using stat_summary
.
plot <- ggplot(data = df, aes(y = dust, x = wind)) +
geom_boxplot(fatten = NULL) +
stat_summary(fun.y = mean, geom = "errorbar", aes(ymax = ..y.., ymin = ..y..),
width = 0.75, size = 1, linetype = "solid")
print(plot)
Output using fatten = NULL
As you can see, the above method plots just fine, but when you evaluate the code it will output some warning messages because fatten
is not really expected to take a NULL
value.
The upside is that this method is possibly a bit more flexible, as we are essentially "erasing" the median line and adding in whatever we want. For example, we could also choose to keep the median, and add the mean as a dashed line.