Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change order of models in a ggplot (dotwhisker)

Tags:

r

ggplot2

To my knowledge, there are many threads that deal with the order of legends or factors in ggplot. However, I failed to find advises how to change the order of multiple models within a single plot. The dotwhisker-package by Solt & Hu integrates ggplot for their plots.

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

The plot looks like this: https://imgur.com/JkUcy7t

The problem with this plot is that the coefficients and CIs of model 3, which should be the last presented values, are presented first in each row.

I want the coefficients in each row to be presented chronologically. That is, M1 coefficients+CI above M2 coefficients+CI. And M2 coefficients+CI above M3 coefficients+CI. More plainly: The red line should be above the green line, which should be above the blue line.

The use of the models as factor hasn't proven useful.

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

Do you have any idea how I could display the models in a chronological order in each row? I hope you understand what I mean and I thank you in advance.

Note: I adapted examples from here: https://cran.r-project.org/web/packages/dotwhisker/vignettes/dotwhisker-vignette.html.

like image 442
Felix Goldberg Avatar asked Nov 07 '22 05:11

Felix Goldberg


1 Answers

This works:

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

Explanation:

The models on the plot are sorted from bottom to top. I changed this by sorting them in descending order and making sure their factor levels are sorted that way: %>% arrange(desc(model)) threeM$model <- factor (threeM$model) The models on the legend are sorted from top to bottom. This can be changed defining breaks: scale_color_brewer(palette="Set1", breaks=c("M1","M2","M3"))

like image 138
Maksym Avatar answered Nov 13 '22 02:11

Maksym