使用plot_models()绘制指定系数多图及分图时遇错误求助
问题分析与解决方案
错误原因
这个错误的核心是sjPlot无法正确读取模型的元信息(比如是否为零膨胀模型、是否包含离散参数),导致逻辑判断时出现类型不匹配。常见诱因包括:
- 版本兼容性问题:你参考的是2020年的旧版指南,当前使用的
sjPlot版本与旧版代码逻辑不兼容,模型信息的读取方式已发生变化。 - 变量处理干扰模型解析:
set_label对响应变量的标签设置,或to_factor处理后的因子变量格式,干扰了sjPlot对模型结构的识别。
解决方案
1. 匹配指南对应的sjPlot版本
由于你参考的是2020-03-10的快照文档,建议安装对应时间点的sjPlot版本:
# 安装指定版本的sjPlot(示例为R 3.6的Windows版本,需根据自身R版本调整路径) packageurl <- "https://mran.microsoft.com/snapshot/2020-03-10/bin/windows/contrib/3.6/sjPlot_2.8.3.zip" install.packages(packageurl, repos=NULL, type="source")
2. 简化变量处理,重新拟合模型
去掉可能干扰模型信息读取的标签设置,改用基础R的因子转换方式重新拟合模型:
library(sjPlot) library(ggplot2) data(efc) theme_set(theme_sjplot()) # 用基础R处理响应变量和因子 y <- factor(ifelse(efc$neg_c_7 < median(na.omit(efc$neg_c_7)), 0, 1), labels = c("Low Impact", "High Negative Impact")) df <- data.frame( y = y, sex = factor(efc$c161sex, labels = c("Male", "Female")), dep = factor(efc$e42dep, labels = c("Independent", "Slightly dependent", "Moderately dependent", "Severely dependent")), barthel = efc$barthtot, education = factor(efc$c172code) ) # 重新拟合三个模型 m1 <- glm(y ~., data = df, family = binomial(link = "logit")) m2 <- glm(y ~ sex + dep, data = df, family = binomial(link = "logit")) m3 <- glm(y ~ sex + dep + barthel, data = df, family = binomial(link = "logit")) # 尝试绘图 plot_models(m1, m2, m3, terms = c("sex", "dep")) plot_models(m1, m2, m3, facet_grid = TRUE)
3. 手动提取系数后绘图(替代方案)
如果上述方法无效,可以手动提取模型系数信息,用ggplot2自主绘图:
library(broom) library(dplyr) library(ggplot2) # 提取三个模型的系数(转换为优势比) coef_m1 <- tidy(m1, exponentiate = TRUE) %>% mutate(model = "m1") coef_m2 <- tidy(m2, exponentiate = TRUE) %>% mutate(model = "m2") coef_m3 <- tidy(m3, exponentiate = TRUE) %>% mutate(model = "m3") # 合并数据并筛选目标变量 coef_data <- bind_rows(coef_m1, coef_m2, coef_m3) %>% filter(grepl("sex|dep", term)) # 绘制森林图 ggplot(coef_data, aes(x = estimate, y = term, color = model)) + geom_vline(xintercept = 1, linetype = "dashed", color = "gray50") + geom_point(position = position_dodge(width = 0.5)) + geom_errorbarh(aes(xmin = conf.low, xmax = conf.high), position = position_dodge(width = 0.5), height = 0) + theme_sjplot() + labs(x = "Odds Ratio", y = "Variable")
内容的提问来源于stack exchange,提问作者hy9fesh
相关产品推荐
相关产品推荐

