如何添加水平线以显示ggplot2中所有组的均值?

wdk*_*nls 5 r ggplot2

是否可以在不预先创建摘要数据集的情况下将水平线与组均值放置在绘图上?我知道这可行,但是我觉得必须有一种用just做到这一点的方法ggplot2

library(dplyr)
library(ggplot2)
X <- data_frame(
  x = rep(1:5, 3),
  y = c(rnorm(5, 5, 0.5),
        rnorm(5, 3, 0.3),
        rnorm(5, 4, 0.7)),
  grp = rep(LETTERS[1:3], each = 5))

X.mean <- X %>%
  group_by(grp) %>%
  summarize(y = mean(y))

X %>%
  ggplot(aes(x = x, y = y, color = grp)) +
  geom_point(shape = 19) +
  geom_hline(data = X.mean, aes(group = grp, yintercept = y, color = grp)) +
  background_grid()
Run Code Online (Sandbox Code Playgroud)

分组平均线

jlh*_*ard 8

扩展我的评论:

ggplot(X, aes(x = x, y = y, color = grp)) +
  geom_point(shape = 19) +
  stat_smooth(method="lm", formula=y~1, se=FALSE)+
  theme_bw()
Run Code Online (Sandbox Code Playgroud)

所以这应用了一个只有常数项的线性模型,它返回平均值。归功于此答案的基本思想。

编辑:对 OP 非常聪明的建议的回应。

看起来您可以使用分位数回归来生成中位数!

library(quantreg)
ggplot(X, aes(x = x, y = y, color = grp)) +
  geom_point(shape = 19) +
  stat_smooth(method="rq", formula=y~1, se=FALSE)+
  theme_bw()
Run Code Online (Sandbox Code Playgroud)

的基本要求stat_smooth(method=..., ...)是该方法返回一个对象,该对象有一个predict(...)方法。所以这里rq(...)返回一个rq对象并且有一个predict.rq(...)方法。se=TRUE有时您可能会遇到麻烦,因为并非所有预测方法都会返回估计值的标准误差。