gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 13:14:17 29 4
gpt4 key购买 nike

有没有一种方法可以在绘图上放置带有组均值的水平线,而无需提前创建汇总数据集?我知道这可行,但我觉得必须有一种方法可以仅使用 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()

grouped mean lines

最佳答案

扩展我的评论:

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

因此,这应用了仅包含常数项的线性模型,该模型返回平均值。信用 this answer基本思想。

编辑:回应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()

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

关于r - 如何添加水平线显示ggplot2中所有组的平均值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32504313/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com