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

如何为sjPlot::plot_model的fill参数映射更具信息量的值

解决sjPlot绘图显示原始分类标签而非编码值的问题

当用总和编码的分类变量构建模型后,使用sjPlot的plot_model()绘制交互项时,默认会显示编码后的数值(如-0.5、0、0.5),而非原始分类标签。以下是几种可行的解决方法:

方法1:创建带原始标签的因子型编码变量

在生成编码变量时,直接将其转为带原始标签的因子,建模时再转回数值型,既能保证模型计算正确,又能让绘图自动识别原始标签:

library(lme4)
library(sjPlot)
library(ggplot2)

theme_set(theme_sjplot())

# 生成带原始标签的因子编码变量
cake$recipe_recoded <- factor(
  ifelse(cake$recipe == 'A', -0.5,
         ifelse(cake$recipe == 'B', 0,
                ifelse(cake$recipe == 'C', 0.5, NA))),
  levels = c(-0.5, 0, 0.5),
  labels = c("A", "B", "C")  # 替换为你的原始分类标签,比如需求中的"200"、"1200"
)

# 建模时将因子转回数值型
fit <- lmer(angle ~ as.numeric(recipe_recoded) * temp + 
             (1|as.numeric(recipe_recoded):replicate), 
           cake, REML= FALSE)

# 绘图时自动显示原始标签
plot_model(fit, type = 'pred', terms = c('temp', 'recipe_recoded'))

方法2:绘图后手动修改标签

如果已经完成建模,可直接在返回的ggplot对象上修改图例标签:

# 生成基础绘图
p <- plot_model(fit, type = 'pred', terms = c('temp', 'recipe_recoded'))

# 修改填充图例的标签(对应你传入的fill参数)
p + scale_fill_discrete(labels = c("A", "B", "C"))
# 若绘图用颜色分组则替换为:scale_color_discrete(labels = c("A", "B", "C"))

方法3:使用plot_model的transform参数

利用transform参数直接在绘图时映射编码值到原始标签:

library(dplyr)  # 需要dplyr的case_when函数

plot_model(fit, type = 'pred', terms = c('temp', 'recipe_recoded'),
           transform = list(recipe_recoded = function(x) {
             case_when(
               x == -0.5 ~ "A",
               x == 0 ~ "B",
               x == 0.5 ~ "C"
             )
           }))

内容的提问来源于stack exchange,提问作者Pablo Bernabeu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 11:05:20