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

如何用ggplot2绘制混合效应模型随机效应系数及置信区间森林图

实现方案

1. 依赖包准备

你需要先加载lme4(原代码中写的lmer是包内函数,包名实际为lme4)、ggplot2以及用于快速提取随机效应的broom.mixed包:

install.packages(c("ggplot2", "broom.mixed")) # 未安装可先执行此行
library(lme4)
library(ggplot2)
library(broom.mixed)

2. 提取带置信区间的随机效应数据

直接用tidy函数一键导出结构化的随机效应数据集,包含估计值、标准误和95%置信区间:

re_df <- tidy(
  mymodel,
  effects = "ran_vals",
  group = "GE_state",
  conf.int = TRUE,
  conf.level = 0.95
)

3. 绘制分面森林图

和你之前用lattice生成的dotplot逻辑一致,按随机效应类型(截距/itr斜率)分面,x轴自由缩放:

ggplot(re_df, aes(x = estimate, y = level)) +
  # 添加0值参考虚线
  geom_vline(xintercept = 0, linetype = "dashed", color = "gray60", linewidth = 0.8) +
  # 绘制95%置信区间
  geom_errorbarh(aes(xmin = conf.low, xmax = conf.high), height = 0.25, color = "gray30") +
  # 绘制效应值点
  geom_point(size = 2.2, color = "#1f77b4") +
  # 分面展示,x轴自由适配范围
  facet_wrap(~term, scales = "free_x", labeller = as_labeller(c(
    "(Intercept)" = "随机截距",
    "itr" = "itr随机斜率"
  ))) +
  # 主题与标签调整
  labs(x = "效应估计值", y = "GE_state分组") +
  theme_bw() +
  theme(
    strip.background = element_rect(fill = "#f0f0f0"),
    strip.text = element_text(face = "bold", size = 11),
    panel.grid.minor = element_blank()
  )

备选:不依赖broom.mixed的手动提取方法

如果你不想安装额外包,也可以直接从ranef的返回结果中计算置信区间:

# 提取随机效应和条件方差
re <- ranef(mymodel, which = "GE_state", condVar = TRUE)
re_se <- attr(re$GE_state, "postVar")

# 手动整理为数据框
re_df <- data.frame(
  level = rep(rownames(re$GE_state), 2),
  term = rep(c("(Intercept)", "itr"), each = nrow(re$GE_state)),
  estimate = c(re$GE_state[["(Intercept)"]], re$GE_state[["itr"]]),
  se = c(re_se[1, 1, ], re_se[2, 2, ])
)
# 计算95%置信区间
re_df$conf.low <- re_df$estimate - qnorm(0.975) * re_df$se
re_df$conf.high <- re_df$estimate + qnorm(0.975) * re_df$se

整理后的数据框re_df和之前方法输出的结构一致,直接复用上述ggplot代码即可绘图。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 00:51:00