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

如何可视化含二元因变量与预测变量的混合效应模型?

二元变量混合效应模型的可视化方案设计

需求背景

因变量Preselected_0与预测变量N_G_altnt_Q_YN均为二元变量,已拟合嵌套结构的混合效应logistic模型,需要设计美观且信息丰富的可视化方案,期望接近连续变量拟合线+置信带的样式,若二元变量无法适配该样式,可提供替代方案。

原模型与初始绘图代码

模型拟合代码

m_0 <- glmer(Preselected_0 ~ N_G_altnt_Q_YN + (N_G_altnt_Q_YN | File / Person_anon), family = "binomial", 
                    data = df)

初始sjPlot绘图代码

library(sjPlot)

plot_model(m_0, type = "eff", terms = c("N_G_altnt_Q_YN"),
           title = ""
)

可视化解决方案

由于预测变量为二元类型,参考的连续变量拟合线样式并不适配,以下提供两种更适合的可视化方案:

方案1:定制化边际效应点图(推荐)

通过sjPlot调整参数或结合emmeans+ggplot2绘制分组点图,展示不同预测变量水平下因变量的预测概率及置信区间,清晰直观:

用sjPlot快速调整

library(sjPlot)
library(ggplot2)

plot_model(m_0, type = "eff", terms = "N_G_altnt_Q_YN",
           pred.type = "response",  # 输出概率尺度的结果
           ci.lvl = 0.95,
           dot.size = 3,
           line.size = 1.5,
           title = "预测变量对Preselected_0的边际效应",
           axis.title = c("N_G_altnt_Q_YN", "Preselected_0的预测概率"),
           theme = theme_sjplot2()) +
  geom_hline(yintercept = 0.5, linetype = "dashed", color = "gray50")  # 添加概率0.5参考线

用ggplot2定制化绘图

library(lme4)
library(emmeans)
library(ggplot2)

# 计算边际预测概率及置信区间
emm <- emmeans(m_0, ~ N_G_altnt_Q_YN, type = "response")
emm_df <- as.data.frame(emm)

# 绘制点图+误差棒
ggplot(emm_df, aes(x = N_G_altnt_Q_YN, y = prob)) +
  geom_point(size = 4, color = "#2c3e50") +
  geom_errorbar(aes(ymin = lower.CL, ymax = upper.CL), width = 0.2, linewidth = 1, color = "#2c3e50") +
  labs(title = "预测变量对Preselected_0的边际效应",
       x = "N_G_altnt_Q_YN",
       y = "Preselected_0的预测概率") +
  theme_minimal() +
  theme(plot.title = element_text(hjust = 0.5, size = 14, face = "bold"),
        axis.title = element_text(size = 12),
        axis.text = element_text(size = 10)) +
  ylim(0, 1)

方案2:补充随机效应可视化

为了更全面展示模型信息,可添加嵌套随机效应的分布可视化:

plot_model(m_0, type = "re", sort.est = TRUE,
           title = "嵌套随机效应的分布",
           axis.title = c("随机效应估计值", "分组"))

样式适配参考(解释性较弱)

若坚持接近参考的折线样式,可将二元变量编码为0/1数值变量后绘制拟合线,但这种方式对二元变量的解释性较差,仅作样式参考:

# 编码二元变量为数值
df$N_G_altnt_Q_YN_num <- as.numeric(df$N_G_altnt_Q_YN) - 1

# 重新拟合模型
m_0_num <- glmer(Preselected_0 ~ N_G_altnt_Q_YN_num + (N_G_altnt_Q_YN_num | File / Person_anon), 
                 family = "binomial", data = df)

# 绘制拟合线
plot_model(m_0_num, type = "eff", terms = "N_G_altnt_Q_YN_num",
           pred.type = "response", ci.lvl = 0.95,
           line.size = 1.5, dot.size = 3,
           title = "预测变量对因变量的拟合效应(数值编码)",
           axis.title = c("N_G_altnt_Q_YN(0/1)", "Preselected_0的预测概率")) +
  theme_minimal()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 05:22:01