如何用marginaleffects::plot_comparisons()绘制单分类变量对比图
问题描述
我有一个仅包含分类解释变量的线性模型:
linmod <- lm(mpg ~ factor(cyl), data = mtcars) parameters::parameters(linmod) #> Parameter | Coefficient | SE | 95% CI | t(29) | p #> ------------------------------------------------------------------- #> (Intercept) | 26.66 | 0.97 | [ 24.68, 28.65] | 27.44 | < .001 #> cyl [6] | -6.92 | 1.56 | [-10.11, -3.73] | -4.44 | < .001 #> cyl [8] | -11.56 | 1.30 | [-14.22, -8.91] | -8.90 | < .001
需要用marginaleffects::plot_comparisons()绘制和parameters::parameters(linmod, drop = "(Intercept)") |> plot()类似的对比图(即6缸 vs 4缸、8缸 vs 4缸),并将图旋转。但plot_comparisons()似乎要求传入无关的by或condition参数,该如何处理?
解决方案
要实现需求,只需指定plot_comparisons()的variables参数明确对比基准,再用布局参数或ggplot2工具调整旋转效果,无需额外的by/condition参数:
方法一:直接生成旋转后的图表
library(marginaleffects) plot_comparisons( linmod, variables = list(cyl = c("6", "8")), # 指定对比6缸、8缸,默认以参考水平4缸为基准 orientation = "y" # 直接设置纵向布局(旋转效果) )
方法二:返回ggplot对象自定义调整
如果需要更灵活的样式修改,先返回ggplot对象再调整:
library(marginaleffects) library(ggplot2) # 生成基础对比图,不直接绘图 p <- plot_comparisons( linmod, variables = list(cyl = c("6", "8")), draw = FALSE ) # 旋转坐标轴并优化样式 p + coord_flip() + labs(x = "对比组别", y = "系数估计值(95%置信区间)") + theme_minimal()
参数说明
variables = list(cyl = c("6", "8")):指定要对比的分类水平,marginaleffects自动以模型的参考水平(此处为cyl=4)作为基准,生成6vs4、8vs4的对比结果。orientation = "y":直接将图表布局转为纵向,实现旋转效果。draw = FALSE:返回ggplot对象,方便用ggplot2语法自定义样式。
内容的提问来源于stack exchange,提问作者Stefan Hansen
相关产品推荐
相关产品推荐

