我有一个条形图,其中精确的条形高度在数据框中。
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")
现在我想添加两个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")
是
正如我想为任意数量的组执行此操作,我将非常感谢使用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
以独特的x运作; ...
在这种情况下,stat_summary
默认继承了x = x
和group = g
的顶级美学映射,因此它将计算每个x的每个x的平均y值,从而产生大量水平线。将x = 1
添加到stat_summary
的映射会覆盖x = x
(同时保留group = g
),因此我们得到g的每个值的单个均值y值。