如何用lmer和sjPlot绘制含随机斜率与截距的混合效应模型图?
解决方法
方法1:用ggpredict结合ggplot手动绘制
sjPlot当前版本的plot_model简化调用可能未正确触发随机斜率的绘制,可以直接用底层的ggpredict函数提取预测值,再用ggplot组合图形:
library(lmerTest) # 也可替换为lme4,不影响核心功能 library(sjPlot) library(ggplot2) library(readr) df <- read_csv("anonymized_test.csv") m1 <- lmer(DV ~ IV + (1 + IV| iso), data = df) # 提取包含随机截距+斜率的分组预测值 re_pred <- ggpredict(m1, terms = c("IV", "iso"), type = "re") # 提取整体固定效应的预测值 fe_pred <- ggpredict(m1, terms = "IV", type = "fe") # 组合绘图 ggplot() + # 绘制每个分组的随机斜率线 geom_line(data = re_pred, aes(x = x, y = predicted, color = group)) + # 绘制加粗的固定效应参考线 geom_line(data = fe_pred, aes(x = x, y = predicted), color = "black", size = 1.2) + labs(x = "IV", y = "Predicted DV", color = "iso") + theme_minimal()
方法2:手动提取模型参数计算预测值
如果不想依赖sjPlot的封装函数,可以直接从模型中提取参数计算预测值:
library(lme4) library(ggplot2) library(readr) df <- read_csv("anonymized_test.csv") m1 <- lmer(DV ~ IV + (1 + IV| iso), data = df) # 提取固定效应参数 fixef_vals <- fixef(m1) # 提取各分组的随机效应(截距+斜率) ranef_vals <- ranef(m1)$iso # 生成覆盖IV数据范围的序列用于预测 iv_seq <- seq(min(df$IV), max(df$IV), length.out = 100) # 构建每个分组的预测数据 pred_list <- lapply(rownames(ranef_vals), function(grp) { group_intercept <- fixef_vals[1] + ranef_vals[grp, 1] group_slope <- fixef_vals[2] + ranef_vals[grp, 2] data.frame( iso = grp, IV = iv_seq, predicted = group_intercept + group_slope * iv_seq ) }) re_pred <- do.call(rbind, pred_list) # 构建固定效应预测数据 fe_pred <- data.frame( IV = iv_seq, predicted = fixef_vals[1] + fixef_vals[2] * iv_seq ) # 绘图 ggplot() + geom_line(data = re_pred, aes(x = IV, y = predicted, color = iso)) + geom_line(data = fe_pred, aes(x = IV, y = predicted), color = "black", size = 1.2) + labs(x = "IV", y = "Predicted DV", color = "iso") + theme_minimal()
注意事项
- 你的模型公式
(1 + IV| iso)已经正确指定了随iso变化的随机截距和斜率,且两者存在相关性,模型结构本身无问题。 - sjPlot旧版的废弃功能无法直接恢复,上述两种方法可以实现相同的可视化需求,且灵活性更高。
内容的提问来源于stack exchange,提问作者J.Karl
相关产品推荐
相关产品推荐

