在R中绘制含分类变量的GLMM:获取拟合值与标准误遇阻
解决GLMM饵料类型与物种总数的绘图问题
针对你用glmer构建的Poisson混合模型,要绘制仅包含饵料类型(Bait.Type)与物种总数(Total.species..MaxN.)的关联图,核心是获取排除生境(Habitat)随机效应的边际拟合值,以下是具体解决方法:
1. 正确获取拟合值与标准误
默认predict(glmer(...))会包含随机效应(生境)的影响,导致无法得到仅反映饵料类型的平均拟合结果。需要指定re.form=NA忽略随机效应,结合对数尺度计算标准误:
# 在对数尺度获取拟合值和标准误 log_fit <- predict(glm1, type="link", re.form=NA) log_se <- predict(glm1, type="link", re.form=NA, se.fit=TRUE)$se.fit # 转换回响应尺度(Poisson模型的原始计数尺度) fit <- exp(log_fit) se.fit <- exp(log_fit) * log_se # 链式法则计算响应尺度标准误 # 构建去重后的预测数据框(保留每个饵料类型的唯一拟合值) pred_df_unique <- unique(data.frame( Bait.Type = df$Bait.Type, fit = fit, se.fit = se.fit ))
若嫌手动转换麻烦,推荐用emmeans包直接获取边际均值,操作更简洁:
library(emmeans) # 获取每个Bait.Type的边际均值(响应尺度)及置信区间 emm <- emmeans(glm1, ~ Bait.Type, type="response") pred_df <- as.data.frame(emm)
2. 绘制饵料类型与物种总数的关联图
用ggplot2绘制原始数据点+拟合值+置信区间:
方法一:使用手动计算的拟合值
library(ggplot2) ggplot() + # 原始数据点添加抖动避免重叠 geom_jitter(data=df, aes(x=Bait.Type, y=Total.species..MaxN.), alpha=0.6, width=0.2) + # 拟合值点 geom_point(data=pred_df_unique, aes(x=Bait.Type, y=fit), color="red", size=3) + # 95%置信区间 geom_errorbar(data=pred_df_unique, aes(x=Bait.Type, ymin=fit-1.96*se.fit, ymax=fit+1.96*se.fit), color="red", width=0.2) + labs(x="饵料类型", y="物种总数(MaxN)", title="饵料类型对物种总数的影响") + theme_bw()
方法二:使用emmeans输出的结果
library(ggplot2) ggplot() + geom_jitter(data=df, aes(x=Bait.Type, y=Total.species..MaxN.), alpha=0.6, width=0.2) + geom_point(data=pred_df, aes(x=Bait.Type, y=emmean), color="red", size=3) + geom_errorbar(data=pred_df, aes(x=Bait.Type, ymin=lower.CL, ymax=upper.CL), color="red", width=0.2) + labs(x="饵料类型", y="物种总数(MaxN)", title="饵料类型对物种总数的影响") + theme_bw()
关键说明
re.form=NA:强制忽略随机效应,得到的是基于固定效应的平均拟合结果,符合“移除生境相关部分”的需求。- Poisson模型默认在对数尺度输出拟合值,必须转换回响应尺度(计数)才能和原始数据匹配。
emmeans包自动处理链接函数转换和置信区间计算,大幅简化操作。
内容的提问来源于stack exchange,提问作者Katie OToole
相关产品推荐
相关产品推荐

