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

如何为lme4线性混合模型的预测回归线添加误差带

解决方案

你当前手动提取系数、逐个绘制线段的方式效率较低,也不好直接计算连续的置信区间来绘制误差带,推荐通过生成预测网格+计算预测值置信区间的方法实现,以下是可直接运行的修改后代码:

如果你没有安装ggeffects包,先运行安装:

install.packages("ggeffects")

替换你原来的手动提取系数、绘图部分的代码即可:

library(ggeffects)

# 生成每个物种在Temp范围内的预测值及95%置信区间,re.form=NA表示仅计算固定效应的总体预测
pred_df <- ggpredict(model, terms = c("Temp [n=100]", "Species"), re.form = NA)

# 绘图
ggplot(data, aes(Temp, Onset, colour = Species, shape = Transect)) +
  geom_point(size = 0.9, position = position_jitter(width = 0.1, height = 2)) +
  # 添加置信误差带,alpha设置透明度避免遮挡点
  geom_ribbon(data = pred_df, aes(x = x, y = predicted, ymin = conf.low, ymax = conf.high, 
                                  fill = group, colour = NULL), alpha = 0.2, inherit.aes = FALSE) +
  # 添加回归线,无需再手动逐个写geom_segment
  geom_line(data = pred_df, aes(x = x, y = predicted, colour = group), linewidth = 0.4, inherit.aes = FALSE) +
  theme_bw() +
  scale_shape_manual(labels = c("A", "B", "C"), values = c(16,17,15), name = "Transect:") +
  scale_colour_manual(values = c("red", "green", "blue"), labels = c("D", "E", "F"), name = "Species:") +
  scale_fill_manual(values = c("red", "green", "blue"), labels = c("D", "E", "F"), name = "Species:") +
  labs(x = "Temperature [°C]", y = "DOY", colour = "Species", shape = "Transect", fill = "Species") +
  theme(axis.title.x = element_text(size = 10), axis.title.y = element_text(size = 10), 
        axis.text.x = element_text(size =8), axis.text.y = element_text(size =8)) +
  coord_cartesian(xlim = c(3, 12), expand = TRUE)

代码说明

  • ggpredict的terms参数中Temp [n=100]表示在Temp的观测范围内均匀取100个点做预测,保证回归线和误差带平滑
  • re.form = NA是为了和你原来手动绘制的回归线保持一致,只使用固定效应计算总体水平的预测值,如果需要纳入随机效应的变异可以移除该参数
  • inherit.aes = FALSE是因为预测数据集pred_df的列名和原始数据集不一样,避免继承全局aes报错
  • 如果你不想额外安装包,也可以手动构建预测网格,用predict函数结合模型的方差协方差矩阵计算置信区间,只是代码量更大容易出错

内容的提问来源于stack exchange,提问作者T.Tree

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 09:48:03