R语言 如何在不更改底层数据的情况下更改plot_model中的facet顺序?

o7jaxewo  于 2023-06-27  发布在  其他
关注(0)|答案(1)|浏览(121)

我使用sjPlot中的plot_model制作了一个预测的边际效应图,显示了在变量高度的选定水平上的预测,我命名这些水平是为了说明它们分别是-1 SD、平均值和+1 SD。不幸的是,由于字母顺序,当高度包括负值和正值并且平均值是比-1SD更接近零的负值时,面将不会以前面列出的方式排序。因此,我不得不以某种方式重新排序它们。由于高度实际上是数字,并且我只手动选择了要在图中显示的特定高度值,因此我不认为可以通过重新排序基础数据来实现这一点,因为变量不是因子。除了把它转换成一个因子并重新排序所有的水平?但我希望有一个更方便的解决方案,不需要修改底层数据。

library(dplyr)
library(sjPlot)

#specifying the model
model = lm(mass ~ gender*species*height, data = starwars[starwars$species == "Human" | starwars$species == "Droid" | starwars$species == "Twi'lek",])

#plotting predictions at three specified levels of height, let's pretend they're -1 SD, mean and +1 #SD
plot = plot_model(model, type = "pred", terms = c("species", "gender", "height [-2, -1, 1]"), ci.lvl=0.95) 

#renaming facets to specify that they represent -1 SD, mean, and +1 SD
plot$data$facet <- ifelse(plot$data$facet == "height = -2", "height = -2 (-1 SD)",
                             ifelse(plot$data$facet == "height = -1", "height = -1 (mean)",
                                    ifelse(plot$data$facet == "height = 1", "height = 1 (+1 SD)",  99)))

oxf4rvwz

oxf4rvwz1#

您可以通过将数据中的facet变量作为因子来实现这一点,因子中的水平按您想要的顺序排列。

library(dplyr)
library(sjPlot)

#specifying the model
model = lm(mass ~ gender*species*height, data = starwars[starwars$species == "Human" | starwars$species == "Droid" | starwars$species == "Twi'lek",])

#plotting predictions at three specified levels of height, let's pretend they're -1 SD, mean and +1 #SD
plot = plot_model(model, type = "pred", terms = c("species", "gender", "height [-2, -1, 1]"), ci.lvl=0.95) 
#> Warning in predict.lm(model, newdata = data_grid, type = "response", se.fit =
#> se, : prediction from rank-deficient fit; attr(*, "non-estim") has doubtful
#> cases

plot$data$facet <- factor(case_when(
  plot$data$facet == "height = -2" ~ "height = -2 (-1 SD)", 
  plot$data$facet == "height = -1" ~ "height = -1 (mean)", 
  plot$data$facet == "height = 1" ~ "height = 1 (+1 SD)", 
), levels=c("height = -2 (-1 SD)", "height = -1 (mean)", "height = 1 (+1 SD)"))

plot

创建于2023-06-22带有reprex v2.0.2

相关问题