You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R基础绘图中为两个GLM模型添加阴影置信区间?

给二项GLM拟合线添加阴影置信区间

步骤1:构造预测数据集

首先在自变量取值范围内生成连续预测序列,覆盖原始数据的完整范围:

# 生成间隙宽度的连续序列
larg_seq <- seq(min(df$LargDiscon), max(df$LargDiscon), length.out = 100)
# 针对带交互项的gt模型,组合所有位点水平
pred_gt <- expand.grid(LargDiscon = larg_seq, Site = unique(df$Site))
# 针对全局模型gt2,仅保留间隙宽度序列
pred_gt2 <- data.frame(LargDiscon = larg_seq)

步骤2:计算拟合值与置信区间

利用predict()函数获取链接尺度的拟合值和标准误,再通过plogis()转换回概率尺度:

# 处理带交互项的gt模型
gt_pred <- predict(gt, newdata = pred_gt, type = "link", se.fit = TRUE)
pred_gt$fit <- plogis(gt_pred$fit)
# 计算95%置信区间上下限
pred_gt$lower <- plogis(gt_pred$fit - 1.96 * gt_pred$se.fit)
pred_gt$upper <- plogis(gt_pred$fit + 1.96 * gt_pred$se.fit)

# 处理全局模型gt2
gt2_pred <- predict(gt2, newdata = pred_gt2, type = "link", se.fit = TRUE)
pred_gt2$fit <- plogis(gt2_pred$fit)
pred_gt2$lower <- plogis(gt2_pred$fit - 1.96 * gt2_pred$se.fit)
pred_gt2$upper <- plogis(gt2_pred$fit + 1.96 * gt2_pred$se.fit)

步骤3:基础绘图实现阴影区间与拟合线

先绘制原始观测数据,再用polygon()绘制置信区间阴影,最后叠加拟合线:

# 初始化画布,设置坐标轴范围
plot(nRF01 ~ LargDiscon, data = df, col = df$Site, pch = 16, 
     xlab = "间隙宽度", ylab = "穿越概率", ylim = c(0,1))

# 绘制gt模型的位点专属置信区间与拟合线
for(s in unique(pred_gt$Site)){
  sub_data <- subset(pred_gt, Site == s)
  # 绘制半透明阴影置信区间
  polygon(c(sub_data$LargDiscon, rev(sub_data$LargDiscon)), 
          c(sub_data$lower, rev(sub_data$upper)), 
          col = adjustcolor(which(unique(df$Site)==s), alpha.f = 0.2),
          border = NA)
  # 绘制拟合线
  lines(sub_data$LargDiscon, sub_data$fit, col = which(unique(df$Site)==s), lwd=2)
}

# 绘制gt2模型的全局置信区间与拟合线
polygon(c(pred_gt2$LargDiscon, rev(pred_gt2$LargDiscon)), 
        c(pred_gt2$lower, rev(pred_gt2$upper)), 
        col = adjustcolor("gray", alpha.f = 0.2),
        border = NA)
lines(pred_gt2$LargDiscon, pred_gt2$fit, col = "gray", lwd=2, lty=2)

# 添加图例区分模型与位点
legend("topright", legend = c(unique(df$Site), "全局模型"),
       col = c(1:length(unique(df$Site)), "gray"),
       lwd = 2, pch = c(rep(16, length(unique(df$Site))), NA),
       lty = c(rep(1, length(unique(df$Site))), 2))

关键说明

  • adjustcolor()用于调整阴影透明度,避免遮挡原始数据和拟合线
  • 二项GLM必须在链接尺度计算标准误,再转换回响应尺度(概率),直接在概率尺度计算会导致置信区间超出[0,1]范围
  • 若需调整置信水平,替换1.96为对应分位数(如99%置信水平用2.576)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 17:37:13