在回归线 R 中添加 +- 2 SE

Add +- 2 SE in regression line R

我想知道是否可以在 R 中绘制一条回归线,包括 +- 2* 标准误差。 例如,使用 iris :

library(ggplot2)
ggplot(iris, aes(x = Petal.Length, y = Sepal.Width))+geom_smooth(method=lm, color="black")+ theme_bw()

输出是:

如何(如果可能)将灰色区域扩展为标准误差两倍的值?

实现您想要的结果的一个选项是通过 stat_smooth 手动添加置信区间并使用 after_stat:

library(ggplot2)
ggplot(iris, aes(x = Petal.Length, y = Sepal.Width)) +
  geom_smooth(method = lm, color = "black", se = FALSE) +
  stat_smooth(aes(ymin = after_stat(y - 2 * se), ymax = after_stat(y + 2 * se)), geom = "ribbon", method = lm, fill = "grey60", alpha = .4) +
  theme_bw()
#> `geom_smooth()` using formula 'y ~ x'
#> `geom_smooth()` using formula 'y ~ x'