如何使用R的interactions包绘制二元交互效应分面图
使用R语言interactions包的cat_plot实现二元交互分面图
我在使用R语言interactions包中的cat_plot函数(ggplot的封装工具)绘制两个分类变量的二元交互效应图,基于diamonds数据集的基础实现代码如下:
require(interactions) data("diamonds") m <- glm(price ~ cut*color, data = diamonds) cat_plot(m, pred = cut, modx = color, geom = "bar", colors = "Set1")
运行后即可得到对应的可视化结果,但我希望生成分面图,将每个cut类别单独展示以降低解读难度。三元交互效应可以通过facet.modx = TRUE参数实现,但我在二元交互场景下运行如下代码时:
cat_plot(m, pred = cut, modx = color, geom = "bar", colors = "Set1", facet.modx = TRUE)
出现如下报错:
Error in prep_data(model = model, pred = pred, modx = modx, pred.values = pred.values, : formal argument "facet.modx" matched by multiple actual arguments
我实际使用的数据集对应的是glmer模型,因此希望尽量在interactions包的框架下实现该需求。
尝试方案1
根据@stefan的建议,我尝试了叠加ggplot分面图层的语法:
cat_plot(m, pred = cut, modx = color, geom = "bar", colors = "Set1") + facet_wrap(~cut)
得到的结果几乎符合预期,但x轴仍然保留了所有cut类别的刻度,仅隐藏了对应柱形,我理想的效果是将color类别放在x轴上。
业务场景复现
我使用更贴近实际业务场景的模拟数据复现了问题,数据包含二分类结局、glmer随机效应等结构:
require(lme4) require(interactions) set.seed(123) id <- rep(1:150, each = 4) condition <- rep(c("a", "b", "c"), each = 4, times = 50) cat_mod <- rep(c("cat_1", "cat_2", "cat_3", "cat_4"), each = 1, length.out = 600) control_mod <- rep(c("control_1", "control_2"), each = 4, length.out = 600) binary_choice <- rbinom(600, 1, 0.5) simdat <- data.frame(id, condition, cat_mod, binary_choice, control_mod) m <- glmer(binary_choice ~ condition*cat_mod + control_mod + (1 | id), family=binomial, data = simdat) cat_plot(m, pred = condition, modx = cat_mod, geom = "bar", colors = "Set1")
运行后得到对应交互图,我希望保留y轴的响应尺度,且保留模型对随机截距的拟合结果,因此不想直接使用ggplot绘图,而interactions包原生支持广义线性混合模型(GLMM),使用起来非常便捷。
最终解决方案
根据@RStam的建议微调代码,统一所有y轴的尺度,同时移除了底部重复的分面标签,最终代码如下:
cat_plot(m, pred = condition, modx = cat_mod, geom = "bar", colors = "Set1") + scale_x_discrete(labels = c(a = " ", b = " ", c = " ")) + facet_wrap(condition~., scales= "free_x")
运行后即可得到符合预期的分面交互图。
内容的提问来源于stack exchange,提问作者becbot
相关产品推荐
相关产品推荐

