如何使用“level”生成 geom_smooth 中的置信区间?

sha*_*roz 5 r ggplot2

我无法模拟如何stat_smooth计算其置信区间。

让我们生成一些数据和一个简单的模型:

library(tidyverse)    
# sample data
df = tibble(
  x = runif(10),
  y = x + rnorm(10)*0.2
)

# simple linear model
model = lm(y ~ x, df)
Run Code Online (Sandbox Code Playgroud)

现在用于predict()生成值和置信区间

# predict 
df$predicted = predict(
  object = model,
  newdata = df
)

# predict 95% confidence interval
df$CI = predict(
  object = model,
  newdata = df,
  se.fit = TRUE
)$se.fit * qnorm(1 - (1-0.95)/2)
Run Code Online (Sandbox Code Playgroud)

请注意,qnorm 用于从标准误差扩展到 95% CI

绘制数据(黑点)、geom_smooth(黑线 + 灰带)和预测带(红线和蓝线)。

ggplot(df) +
  aes(x = x, y = y) +
  geom_point(size = 2) +
  geom_smooth(method = "lm", level = 0.95, fullrange = TRUE, color = "black") +
  geom_line(aes(y = predicted + CI), color = "blue") + # upper
  geom_line(aes(y = predicted - CI), color = "red") + # lower
  theme_classic()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

红线和蓝线应与丝带的边缘相同。我究竟做错了什么?

sha*_*roz 5

正如 @Dason 的评论中所发表的,答案是 geom_smooth 使用 t 分布,而不是正态分布。

在我原来的问题中,qnorm(1 - (1-0.95)/2)用替换qt(1 - (1-0.95)/2, nrow(df))以使行匹配。