如何将sjPlot::plot_model中的颜色变量拆分为等宽区间
将sjPlot::plot_model中的颜色变量拆分为等宽区间
虽然主效应的方向可通过估计值的符号解读,但交互效应的解读通常需要借助可视化图表。R包sjPlot可简化这一任务,例如使用plot_model()函数绘制两个连续变量间的交互效应:
library(lme4) #> Loading required package: Matrix library(sjPlot) #> Learn more about sjPlot with 'browseVignettes("sjPlot")'. library(ggplot2) theme_set(theme_sjplot()) # Create data partially based on code by Ben Bolker set.seed(101) spin = runif(800, 1, 24) trait = rep(1:40, each = 20) ID = rep(1:80, each = 10) testdata <- data.frame(spin, trait, ID) testdata$fatigue <- testdata$spin * testdata$trait / rnorm(800, mean = 6, sd = 2) # Model fit = lmer(fatigue ~ spin * trait + (1|ID), data = testdata, REML = TRUE) #> boundary (singular) fit: see help('isSingular') plot_model(fit, type = 'pred', terms = c('spin', 'trait')) #> Warning: Ignoring unknown parameters: linewidth

创建于2023-06-24,使用reprex v2.0.2
问题
如何将sjPlot::plot_model()中的颜色变量拆分为等宽区间?
解决方案
你可以通过两种简单方式实现颜色变量的等宽区间拆分:
方法1:手动对变量分箱后可视化
先用cut()函数把连续变量trait拆成等宽区间,再将分箱后的变量作为分组项传入plot_model():
# 将trait分成5个等宽区间,包含最小值 testdata$trait_bin <- cut(testdata$trait, breaks = 5, include.lowest = TRUE) # 基于原模型,用分箱后的变量绘制交互效应图 plot_model(fit, type = 'pred', terms = c('spin', 'trait_bin'))
方法2:直接在plot_model()中指定分箱数量
利用plot_model()的terms参数语法,在变量名后加[n]即可自动生成n个等宽区间,比如分成5个区间:
plot_model(fit, type = 'pred', terms = c('spin', 'trait [5]'))
这样生成的图会自动将trait按等宽区间分组,不同区间对应不同颜色的线条,清晰展示交互效应的差异。
内容的提问来源于stack exchange,提问作者Pablo Bernabeu
相关产品推荐
相关产品推荐

