R中绘制lmer模型:替换轴标签、添加对比图及整合数据框
解决方案
1. 手动构建预测数据框
模型里用的是time4(即time^4),所以得先做一个包含原始time的预测数据集,同时计算出模型需要的time4列,这样模型才能生成对应预测值:
# 生成覆盖原始time范围的序列,步长按需调整 pred_data <- data.frame(time = seq(-10, 10, by = 0.5)) # 计算模型所需的time4变量 pred_data$time4 <- pred_data$time^4 # 若模型还有其他固定效应(比如分组变量),要设置为均值或典型值 # 示例:pred_data$group <- mean(原始数据框$group)
2. 从模型生成预测值
用predict()函数分别从两个模型提取固定效应的预测值(加re.form = NA忽略随机效应,需要的话可以去掉):
# 假设两个模型分别是mod1和mod2 pred_data$pred_mod1 <- predict(mod1, newdata = pred_data, re.form = NA) pred_data$pred_mod2 <- predict(mod2, newdata = pred_data, re.form = NA)
3. 用ggplot2绘制合并图
ggplot2能轻松整合两个模型的结果,还能精准控制显示范围:
library(ggplot2) ggplot() + # 绘制第一个模型的完整曲线 geom_line(data = pred_data, aes(x = time, y = pred_mod1), color = "blue", linewidth = 1) + # 绘制第二个模型仅time≥0的部分 geom_line(data = subset(pred_data, time >= 0), aes(x = time, y = pred_mod2), color = "red", linewidth = 1, linetype = "dashed") + # 设置坐标轴和标题 labs(x = "Time", y = "预测因变量值", title = "两个模型的Time效应对比") + theme_minimal()
4. plot_model的替代方案
如果非要用plot_model(),可以手动传递预测数据,再合并图像:
library(sjPlot) library(gridExtra) # 生成两个模型的单独效应图 p1 <- plot_model(mod1, terms = "time", type = "pred", newdata = pred_data) p2 <- plot_model(mod2, terms = "time", type = "pred", newdata = subset(pred_data, time >= 0)) # 合并到同一窗口 grid.arrange(p1, p2, ncol = 1)
最小示例验证
用模拟数据跑一遍完整流程,确保可行:
library(lmerTest) library(ggplot2) # 模拟数据 set.seed(123) dat <- data.frame( id = rep(1:50, each = 10), time = rep(-5:4, 50), y = rnorm(500) + 0.1*(rep(-5:4,50))^4 + rnorm(50, 0, 0.5)[rep(1:50, each=10)] ) dat$time4 <- dat$time^4 # 构建两个模型 mod1 <- lmer(y ~ time4 + (1|id), data = dat) mod2 <- lmer(y ~ time4 + (1|id), data = subset(dat, time >=0)) # 生成预测数据 pred_data <- data.frame(time = seq(-5,4,by=0.2)) pred_data$time4 <- pred_data$time^4 # 生成预测值 pred_data$pred1 <- predict(mod1, newdata = pred_data, re.form=NA) pred_data$pred2 <- predict(mod2, newdata = pred_data, re.form=NA) # 绘图 ggplot(pred_data, aes(x=time)) + geom_line(aes(y=pred1), color="darkblue", linewidth=1) + geom_line(data=subset(pred_data, time>=0), aes(y=pred2), color="darkred", linewidth=1, linetype="dashed") + labs(x="Time", y="预测Y值") + theme_bw()
内容的提问来源于stack exchange,提问作者Manuel Böhm
相关产品推荐
相关产品推荐

