使用geom_bar和stat =“identity”绘制hline的平均值

问题描述 投票:1回答:1

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

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")

enter image description here

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

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")

enter image description here

正如我想为任意数量的组执行此操作,我将非常感谢使用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")

提前致谢!

编辑:

  • 添加了数据集
  • 评论结果代码
  • 改变了数据和情节以澄清问题
r ggplot2 mean geom-bar
1个回答
0
投票

如果我理解你的问题,你的第一种方法就是:

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")

plot

根据stat_summary的帮助文件:

stat_summary以独特的x运作; ...

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

© www.soinside.com 2019 - 2024. All rights reserved.