在ggplot(dotwhisker)中更改模型的顺序

时间:2018-06-25 18:23:29

标签: 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"))

情节看起来像这样: 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"))

您知道如何在每一行中按时间顺序显示模型吗?希望您能理解我的意思,在此先感谢您。

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

2 个答案:

答案 0 :(得分:0)

这有效:

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")) 

说明:

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

答案 1 :(得分:0)

好点。当 Hu recently noticed the issue 在我们自己的工作中使用时,我想到的解决方案是将 guide = guide_legend(reverse = TRUE) 参数用于 scale_color

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

dwplot(threeM) +
scale_color_brewer(palette = "Set1",
guide = guide_legend(reverse = TRUE)) +
theme(legend.title=element_blank(),
panel.background = element_rect(fill = "white"), 
panel.grid.major.x = element_line(colour="grey"))

dwplot with models ordered correctly

We'll work on getting this fixed, though.