【发布时间】:2019-02-19 04:06:23
【问题描述】:
我有一个条形图,其中确切的条形高度在数据框中。
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()+geom_bar()的命令吗?还是什么? -
抱歉,忘记添加数据集。我想要一个像 ggplot() + geom_bar() + stat_summary(geom="hline") 这样的解决方案