如何用sjPlot/ggeffects取预测后在ggplot2绘制混合模型交互效应
提取交互效应预测结果并使用ggplot2可视化
先加载所需依赖包并拟合模型:
library(glmmTMB) library(ggeffects) library(sjPlot) library(ggplot2) model <- glmmTMB(total_count ~ mean_temp*lwd_duration + (1|year), family = nbinom1, data=df)
方法1:用ggeffects生成预测数据集后绘图
ggeffects的ggpredict()能直接输出包含预测值、置信区间的结构化数据,完全适配ggplot2:
# 获取交互效应预测数据,按lwd_duration的四分位数分组 pred_data <- ggpredict(model, terms = c("mean_temp", "lwd_duration [quartile]")) # 用ggplot2可视化 ggplot(pred_data, aes(x = x, y = predicted, color = group)) + geom_line(linewidth = 1) + # 添加置信区间带 geom_ribbon(aes(ymin = conf.low, ymax = conf.high, fill = group), alpha = 0.2, color = NA) + labs( x = "平均温度 (mean_temp)", y = "预测总数量 (total_count)", color = "低温持续时长分位数", fill = "低温持续时长分位数" ) + theme_minimal()
如果需要自定义lwd_duration的分组值,把[quartile]换成具体数值即可,比如[50, 100, 150]。
方法2:用sjPlot提取预测数据后绘图
sjPlot的plot_model()支持返回预测数据集,你可以基于这个数据用ggplot2自由调整样式:
# 提取交互效应的预测数据 sj_pred_data <- plot_model( model, type = "int", terms = c("mean_temp", "lwd_duration [quartile]"), return_data = TRUE ) # 用ggplot2绘图 ggplot(sj_pred_data, aes(x = x, y = predicted, color = group)) + geom_line(linewidth = 1) + geom_ribbon(aes(ymin = conf.low, ymax = conf.high, fill = group), alpha = 0.2, color = NA) + labs( x = "平均温度 (mean_temp)", y = "预测总数量 (total_count)", color = "低温持续时长分位数", fill = "低温持续时长分位数" ) + theme_bw()
内容的提问来源于stack exchange,提问作者Ahsk
相关产品推荐
相关产品推荐

