I want to plot boxplots for several categories and I found very handy if there is a ribbon showing the mean +/- standard deviation for the whole dataset.
I can easily get those values and put them in the plot using the geom_hline()
function, however, I want the area between mean(x) + sd(x)
and mean(x) - sd(x)
to be coloured for better visibility. I was thinking adding geom_ribbon()
there, however I crashed into a problem that my values a cathegorical and I want those lines to fully cover the background on x axis.
library(tidyverse)
library(reshape2)
df <- data.frame(
a = rnorm(1000, 20, 40),
b = rnorm(1000, 100, 40)
)
df
df <- melt(df)
df %>%
ggplot(aes(variable, value)) +
geom_hline(yintercept = c(
mean(df$value) - sd(df$value),
mean(df$value) + sd(df$value)
)) +
geom_hline(yintercept = mean(df$value), size = 3, col = "red") +
geom_boxplot()