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

分组条形图展示glm拟合值及置信区间的报错排查

问题分析与修正

你的代码存在几个关键错误,导致置信区间无法正确生成:

1. 模型变量与绘图变量不匹配

你构建的mod_time模型只纳入了time作为自变量,但绘图时却以treatment作为x轴分组维度。这意味着模型完全未考虑treatment的影响,拟合值和置信区间自然无法对应到每个treatment-time组合。

2. 置信区间计算逻辑错误

confint(mod_time)返回的是模型系数的置信区间,而非拟合值的置信区间,它的维度和你的数据集行数完全不匹配,因此会出现维度错误。

3. predict函数参数误用

glm的predict函数不支持interval="confidence"参数(这是线性模型lm专属参数),你需要通过se.fit=TRUE获取拟合值的标准误,再手动计算置信区间。


修正后的代码

首先调整模型纳入treatment和time的效应(根据研究需求选择主效应或交互效应),再正确计算每个观测的拟合值与置信区间:

# 构建包含treatment和time交互效应的模型(如需仅主效应,改为~ treatment + time)
mod_full <- glm(cbind(germination, total - germination) ~ treatment * time, data = df, family = binomial)

# 获取拟合值和标准误(type="response"转换为概率尺度)
fit_results <- predict(mod_full, newdata = df, type = "response", se.fit = TRUE)

# 基于标准误计算95%置信区间(正态近似法)
df$fit <- fit_results$fit
df$lower <- fit_results$fit - 1.96 * fit_results$se.fit
df$upper <- fit_results$fit + 1.96 * fit_results$se.fit

# 绘制分组条形图+拟合线+置信区间
ggplot(df, aes(x = treatment, y = germination, fill = time)) +
  geom_col(position = position_dodge(width = 0.9)) +
  geom_line(aes(y = fit, group = time), position = position_dodge(width = 0.9), color = "blue") +
  geom_errorbar(aes(ymin = lower, ymax = upper), position = position_dodge(width = 0.9), width = 0.2) +
  labs(x = "Scarification", y = "Germination/Total", fill = "Time")

补充说明

如果想要更贴合二项分布特性的置信区间,可以先在对数尺度计算区间,再转换回概率尺度:

# 对数尺度计算置信区间再转概率
link_fit <- predict(mod_full, newdata = df, type = "link", se.fit = TRUE)
link_lower <- link_fit$fit - 1.96 * link_fit$se.fit
link_upper <- link_fit$fit + 1.96 * link_fit$se.fit
df$lower <- plogis(link_lower)
df$upper <- plogis(link_upper)
df$fit <- plogis(link_fit$fit)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 00:30:56