使用 geom_bar 和 stat="identity" 在均值处绘制 hline

Plot hline at mean with geom_bar and stat="identity"

我有一个条形图,其中确切的条形高度在数据框中。

df <- data.frame(x=LETTERS[1:6], y=c(1:6, 1:6 + 1), g=rep(x = c("a", "b"), each=6))

ggplot(df, aes(x=x, y=y, fill=g, group=g)) + 
  geom_bar(stat="identity", position="dodge")

现在我想添加 两条 行显示每组所有条的平均值。我得到的一切

ggplot(df, aes(x=x, y=y, fill=g, group=g)) + 
  geom_bar(stat="identity", position="dodge") +
  stat_summary(fun.y=mean, aes(yintercept=..y.., group=g), geom="hline")

因为我也想对任意数量的组执行此操作,所以我将不胜感激仅使用 ggplot 的解决方案。

我想避免这样的解决方案,因为它不纯粹依赖传递给ggplot的数据集,有冗余代码并且在组数上不灵活:

ggplot(df, aes(x=x, y=y, fill=g, group=g)) + 
  geom_bar(stat="identity", position="dodge") +
  geom_hline(yintercept=mean(df$y[df$g=="a"]), col="red") +
  geom_hline(yintercept=mean(df$y[df$g=="b"]), col="green")

提前致谢!

编辑:

如果我正确理解你的问题,你的第一种方法就差不多了:

ggplot(df, aes(x = x, y = y, fill = g, group = g)) + 
  geom_col(position="dodge") + # geom_col is equivalent to geom_bar(stat = "identity")
  stat_summary(fun.y = mean, aes(x = 1, yintercept = ..y.., group = g), geom = "hline")

根据stat_summary的帮助文件:

stat_summary operates on unique x; ...

在这种情况下,stat_summary默认继承了x = xgroup = g的顶级美学映射,所以它会计算平均y值在每个x对于每个g值,导致很多水平线。将 x = 1 添加到 stat_summary 的映射会覆盖 x = x(同时保留 group = g),因此我们得到每个 g 值的单个平均 y 值。