I generate a barplot with geom_col() with two classes separated by color. Then I try to add a mean line for each class.
Here is what I'd like to get:
But with the code below the mean line is for each bar independently what I put to group argument.
Here is a reproducible example:
library(tidyverse)
df = data.frame(
x = 1:10,
y = runif(10),
class = sample(c("a","b"),10, replace=T) %>% factor()
) %>%
mutate(x = factor(x, levels=x[order(class, -y)]))
ggplot(df, aes(x, y, fill=class)) +
geom_col() +
stat_summary(fun.y = mean, geom = "errorbar",
aes(ymax = ..y.., ymin = ..y.., group = class),
width = 1, linetype = "solid")
Please tell me what I'm doing wrong. Or any other way (with ggplot) to achieve this?




