简体   繁体   中英

Flip axis and coefficient points in coefficient plot with dwplot()

I'm using the function "dwplot" from the package "dotwhisker" in order to plot the regression coefficients from some LSDV models. This is my model:

coefisubv <- lm(subv ~ Preelectoral + Electoral + Postelectoral + 
                factor(ccaa)-1, data = datos)

Then I converted it into a dataframe so I can delete the factor(ccaa)-1 variables that I don't need:

coefisubv <- as.data.frame(coefisubv)

After that, I want to flip the order of the axis, so I use the function coord_flip(). Then I also want to change the order of the variables in the X axis with the command vars_order().

dwplot(coefisubv, 
       vars_order = c("Postelectoral", "Electoral", "Preelectoral")) + 
    coord_flip()

Finally, I want to add a line that links the coefficient points in the plot using geom_line()

dwplot(coefisubv, 
       vars_order = c("Postelectoral", "Electoral", "Preelectoral")) + 
    coord_flip() + 
    geom_line(aes(Estimate, term), group=1)

This is the result:

在此处输入图像描述

Unfortunately, as you can see, it seems the geom_line() function doesn't recognize that the order of the variables changed, so it believes the variable "Preelectoral" is the variable "Postelectoral" and "Postelectoral" is "Preelectoral". How can I fix this?

I generally find it easier to use broom::tidy + ggplot2 to build coefficient plots by hand when I want to do something a little bit complicated. In this case, eg

library(tidyverse)
library(broom)
m1 <- lm(mpg ~ hp  + disp + drat + factor(cyl) - 1, mtcars)
tt <- (tidy(m1, conf.int = TRUE) 
     ## drop unwanted terms
     %>% filter(!stringr::str_detect(term, "cyl"))
     ## determine term ordering (alphabetical is default)
     %>% mutate(across(term, ~ factor(., levels = c("hp", "disp", "drat"))))
)
gg1 <- (ggplot(tt)
   +  aes(x=term, y=estimate, ymin = conf.low, ymax = conf.high)
   +  geom_pointrange(colour = "red")
   +  geom_line(aes(group = 1))
)
  • no need to use coord_flip() because we set the plot up with the orientation you wanted in the first place
  • aes(group = 1) in geom_line() makes sure we're connecting points even though the x-axis variable is a factor
  • if you want to use this for a plot with multiple models, purrr::map_dfr is great (name your list of models and use .id = "model" )
  • you can use dotwhisker::by_2sd if you need to standardize coefficients

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM