如何在R的multiplot()函数中指定模型显示顺序?
解决coefplot::multiplot中模型显示顺序不符的问题
在R中使用multiplot()搭配coefplot()绘制多模型系数图时,按mod1至mod9的顺序传入模型,但生成的图中模型并非按输入顺序排列,而是呈现反向字母序。以下是具体解决方法:
原代码
multiplot(mod1, mod2, mod3, mod4, mod5, mod6, mod7, mod8, mod9, intercept = F, zeroType = 1, zeroColor = 'black', title = 'The Effect of Masculinity on Sexism Items', ylab = 'Masculinity Index', plot.shapes = T, xlab = 'Sexism', sort = 'natural', legend.reverse = F, names = c('Control', 'Offend', 'Prob', 'Protect', 'Rescue', 'R/W', 'Equal', 'Hire', 'Harass'), newNames = c(masc_ind = 'Masculinity'))+ scale_color_manual(values = c('green', 'green', 'green', 'blue', 'blue', 'blue', 'red', 'red', 'red'))+ scale_shape_manual(values = c(15,16,17,18,19,0,1,2,5))
生成的图中,模型顺序与names参数指定的自定义名称顺序不符,呈现反向字母排序。
解决方法
multiplot()默认会将模型名称转为因子并按字母序排序,sort = 'natural'仅控制系数的排序,不影响模型顺序。可以通过强制指定x轴离散变量的水平顺序来修正:
方法1:直接在绘图代码后添加scale_x_discrete
在原代码末尾加上一行,指定模型的显示顺序为你定义的names列表顺序:
+ scale_x_discrete(limits = c('Control', 'Offend', 'Prob', 'Protect', 'Rescue', 'R/W', 'Equal', 'Hire', 'Harass'))
完整代码示例:
multiplot(mod1, mod2, mod3, mod4, mod5, mod6, mod7, mod8, mod9, intercept = F, zeroType = 1, zeroColor = 'black', title = 'The Effect of Masculinity on Sexism Items', ylab = 'Masculinity Index', plot.shapes = T, xlab = 'Sexism', sort = 'natural', legend.reverse = F, names = c('Control', 'Offend', 'Prob', 'Protect', 'Rescue', 'R/W', 'Equal', 'Hire', 'Harass'), newNames = c(masc_ind = 'Masculinity'))+ scale_color_manual(values = c('green', 'green', 'green', 'blue', 'blue', 'blue', 'red', 'red', 'red'))+ scale_shape_manual(values = c(15,16,17,18,19,0,1,2,5))+ scale_x_discrete(limits = c('Control', 'Offend', 'Prob', 'Protect', 'Rescue', 'R/W', 'Equal', 'Hire', 'Harass'))
方法2:先构造有序模型列表再传入
将模型放入自定义顺序的列表中,再传入multiplot(),同时配合scale_x_discrete锁定顺序:
# 构造按需求排序的模型列表 model_list <- list( Control = mod1, Offend = mod2, Prob = mod3, Protect = mod4, Rescue = mod5, 'R/W' = mod6, Equal = mod7, Hire = mod8, Harass = mod9 ) # 调用multiplot并指定顺序 multiplot(model_list, intercept = F, zeroType = 1, zeroColor = 'black', title = 'The Effect of Masculinity on Sexism Items', ylab = 'Masculinity Index', plot.shapes = T, xlab = 'Sexism', sort = 'natural', legend.reverse = F, newNames = c(masc_ind = 'Masculinity'))+ scale_color_manual(values = c('green', 'green', 'green', 'blue', 'blue', 'blue', 'red', 'red', 'red'))+ scale_shape_manual(values = c(15,16,17,18,19,0,1,2,5))+ scale_x_discrete(limits = names(model_list))
两种方法的核心都是通过scale_x_discrete(limits = ...)强制x轴(模型轴)按你需要的顺序显示,从而覆盖multiplot()默认的字母排序逻辑。
内容的提问来源于stack exchange,提问作者Kaitlin
相关产品推荐
相关产品推荐

