更改 ggplot 中模型的顺序(点须)

Fel*_*erg 5 r ggplot2

据我所知,有许多线程处理 ggplot 中的图例或因素的顺序。但是,我没有找到有关如何更改单个图中多个模型顺序的建议。Solt & Hu 的 dotwhisker-package 为他们的图集成了 ggplot。

library(dotwhisker)
library(broom)
library(dplyr)

m1 <- lm(mpg ~ wt + cyl + disp + gear, data = mtcars)
m2 <- update(m1, . ~ . + hp) 
m3 <- update(m2, . ~ . + am)

threeM <- rbind(tidy(m1) %>% mutate(model = "M1"), 
                tidy(m2) %>% mutate(model = "M2"), 
                tidy(m3) %>% mutate(model = "M3"))

dwplot(threeM) +
    theme(legend.title=element_blank(), panel.background = element_rect(fill = "white"), 
          panel.grid.major.x = element_line(colour="grey"))
Run Code Online (Sandbox Code Playgroud)

情节是这样的: https://imgur.com/JkUcy7t

此图的问题在于模型 3 的系数和 CI(应该是最后显示的值)在每行中首先显示。

我希望每行中的系数按时间顺序显示。即,M1系数+CI高于M2系数+CI。并且M2系数+CI高于M3系数+CI。更简单地说:红线应该在绿线之上,绿线应该在蓝线之上。

使用模型作为因子并没有被证明是有用的。

threeM$model <- factor (threeM$model, levels = c("M1","M2","M3"), labels = c("M1","M2","M3"))
Run Code Online (Sandbox Code Playgroud)

您知道如何在每一行中按时间顺序显示模型吗?我希望你明白我的意思,我提前感谢你。

注意:我改编了这里的示例:https : //cran.r-project.org/web/packages/dotwhisker/vignettes/dotwhisker-vignette.html

小智 1

这有效:

threeM <- bind_rows(
tidy(m1) %>% mutate(model = "M1"), 
tidy(m2) %>% mutate(model = "M2"), 
tidy(m3) %>% mutate(model = "M3")) %>% arrange(desc(model))

threeM$model <- factor (threeM$model, 
levels = c("M1","M2","M3"), 
labels = c("M1","M2","M3"))

dwplot(threeM) +
theme(legend.title=element_blank(), 
panel.background = element_rect(fill = "white"), 
panel.grid.major.x = element_line(colour="grey")) +
scale_color_brewer(palette="Set1",
breaks=c("M1","M2","M3")) 
Run Code Online (Sandbox Code Playgroud)

解释:

图中的模型从下到上排序。我通过按降序对它们进行排序并确保它们的因子水平按这种方式排序来更改此设置:%>% arrange(desc(model)) threeM$model <- factor (threeM$model)图例上的模型从上到下排序。可以更改定义中断:scale_color_brewer(palette="Set1", breaks=c("M1","M2","M3"))