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

如何用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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 16:35:41