You need to enable JavaScript to run this app. 如何在R语言ggplot中为线性回归叠加90%逐点置信带
优惠活动
大模型
产品
解决方案
定价
更多

如何在R语言ggplot中为线性回归叠加90%逐点置信带

解决方法

你当前使用的geom_smooth()函数默认生成95%置信水平的逐点置信带,只需显式指定level参数为0.9,即可叠加你需要的90%逐点置信带,和你用confint()计算的temp变量90%置信区间匹配。

修正后的完整代码

mod1 = lm(area ~ temp, data = forestfires)
# 输出temp变量的90%置信区间
confint(mod1, 'temp', level=0.90)

ggplot(forestfires)+
  aes(x=temp, y=area)+
  geom_point()+
  # 指定置信水平为0.9,se=TRUE为默认开启置信带的参数可省略
  geom_smooth(method = "lm", level = 0.9)+
  scale_y_log10()+
  ggtitle("Relationship of Area Burned and Temperature")+
  xlab("Temperature")+
  ylab("Area")+
  theme(plot.title = element_text(hjust = 0.5))

可选:手动计算置信带后叠加

如果你需要自定义置信带样式、或者单独提取置信区间数值使用,可以用predict()函数先计算每个温度点对应的拟合值和90%置信区间,再用geom_ribbon()手动叠加:

# 计算拟合值和90%置信区间
pred_df <- predict(mod1, newdata = data.frame(temp = sort(unique(forestfires$temp))), 
                   interval = "confidence", level = 0.9)
pred_df <- as.data.frame(pred_df)
pred_df$temp <- sort(unique(forestfires$temp))

ggplot(forestfires)+
  aes(x=temp, y=area)+
  geom_point()+
  # 手动叠加置信带
  geom_ribbon(data = pred_df, aes(y = fit, ymin = lwr, ymax = upr), alpha = 0.2, fill = "grey")+
  # 叠加拟合线
  geom_line(data = pred_df, aes(y = fit), color = "blue")+
  scale_y_log10()+
  ggtitle("Relationship of Area Burned and Temperature")+
  xlab("Temperature")+
  ylab("Area")+
  theme(plot.title = element_text(hjust = 0.5))

内容的提问来源于stack exchange,提问作者vicxirra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 02:15:07