【问题标题】:Change order of models in a ggplot (dotwhisker)更改 ggplot 中模型的顺序(dotwhisker)
【发布时间】:2018-06-25 18:23:29
【问题描述】:

据我所知,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"))

剧情如下:

此图的问题在于,模型 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

【问题讨论】:

  • 呃,dwplot 函数硬编码了 df[[model_name]] &lt;- factor(dfmod, levels = unique(dfmod)) 行,它重新调整了您的因素。基本上,您无法使用现有功能控制它。您可以创建自己的版本,或尝试破解生成的 ggplot 对象。

标签: r ggplot2


【解决方案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")) 

解释:

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

【讨论】:

  • 您能否解释一下为什么如何它的工作原理?
  • 我猜图中的模型是从下到上排序的。我通过对它们进行降序排序并确保它们的因子水平以这种方式排序来改变这一点: %>% 排列(desc(model)) threeM$model
  • 谢谢!我冒昧地将您的解释编辑到您的答案中,可以随时删除 cmets。
【解决方案2】:

好点子。当 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"))

We'll work on getting this fixed, though.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-15
    • 1970-01-01
    • 2019-04-03
    • 2021-08-19
    • 1970-01-01
    • 2019-12-26
    • 1970-01-01
    相关资源
    最近更新 更多