使用sjPlot绘制交互项预测概率图:CI水平无法更改的问题
解决sjPlot绘制glmer模型预测图时CI水平不生效的问题
问题原因
sjPlot的plot_model(type="pred")对混合效应模型(如glmer)默认计算条件预测值(包含随机截距的变异),此时展示的是预测区间(prediction interval),由pi.lvl参数控制,而非ci.lvl。ci.lvl仅对边际预测值(不考虑随机效应,仅基于固定效应)的置信区间生效。
解决方案1:使用re.form=NA指定边际预测
在plot_model中添加re.form=NA参数,强制计算边际预测,此时ci.lvl参数会正确调整置信区间水平:
library(patchwork) library(lme4) library(sjPlot) data(iris) iris$dummy <- rbinom(150, 1, 0.5) iris$group <- round(runif(150, 1, 4), 0) iris$dummy <- as.factor(iris$dummy) iris$group <- as.factor(iris$group) model <- glmer(dummy ~ (1 | group) + Sepal.Width*Species, family = binomial, data = iris) # 95%置信区间(默认) plot1 <- plot_model(model, type = "pred", terms = c("Sepal.Width[all]", "Species"), re.form = NA) # 80%置信区间 plot2 <- plot_model(model, type = "pred", terms = c("Sepal.Width[all]", "Species"), ci.lvl = 0.8, re.form = NA) plot1 + plot2
解决方案2:直接使用ggpredict函数(更灵活)
sjPlot底层依赖ggeffects包的ggpredict函数生成预测数据,直接调用该函数可更精准控制置信区间:
library(patchwork) library(lme4) library(sjPlot) library(ggeffects) data(iris) iris$dummy <- rbinom(150, 1, 0.5) iris$group <- round(runif(150, 1, 4), 0) iris$dummy <- as.factor(iris$dummy) iris$group <- as.factor(iris$group) model <- glmer(dummy ~ (1 | group) + Sepal.Width*Species, family = binomial, data = iris) # 生成95%置信区间的预测数据 pred1 <- ggpredict(model, terms = c("Sepal.Width[all]", "Species"), ci.lvl = 0.95) # 生成80%置信区间的预测数据 pred2 <- ggpredict(model, terms = c("Sepal.Width[all]", "Species"), ci.lvl = 0.8) # 绘制图形 plot1 <- plot(pred1) plot2 <- plot(pred2) plot1 + plot2
补充说明
如果需要展示包含随机效应的预测区间(而非置信区间),可使用pi.lvl参数替代ci.lvl,同时无需设置re.form=NA:
plot_pred_interval <- plot_model(model, type = "pred", terms = c("Sepal.Width[all]", "Species"), pi.lvl = 0.8)
内容的提问来源于stack exchange,提问作者kris
相关产品推荐
相关产品推荐

