簡體   English   中英

使用 dwplot() 在系數 plot 中翻轉軸和系數點

[英]Flip axis and coefficient points in coefficient plot with dwplot()

我正在使用 package “點須”中的 function “dwplot”,以便 plot 來自某些 LSDV 模型的回歸系數。 這是我的 model:

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

然后我將它轉換成 dataframe 這樣我就可以刪除我不需要的 factor(ccaa)-1 變量:

coefisubv <- as.data.frame(coefisubv)

之后,我想翻轉軸的順序,所以我使用 function coord_flip()。 然后我還想用命令 vars_order() 改變變量在 X 軸上的順序。

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

最后,我想添加一條線,使用 geom_line() 連接 plot 中的系數點

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

這是結果:

在此處輸入圖像描述

不幸的是,正如您所見,geom_line() function 似乎沒有意識到變量的順序發生了變化,因此它認為變量“Preelectoral”是變量“Postelectoral”,“Postelectoral”是“Preelectoral”。 我怎樣才能解決這個問題?

當我想做一些有點復雜的事情時,我通常發現使用broom::tidy + ggplot2構建系數圖更容易。 在這種情況下,例如

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))
)
  • 無需使用coord_flip()因為我們首先將 plot 設置為您想要的方向
  • geom_line()中的aes(group = 1)確保我們連接點,即使 x 軸變量是一個因素
  • 如果你想將它用於具有多個模型的 plot, purrr::map_dfr很棒(命名你的模型列表並使用.id = "model"
  • 如果需要標准化系數,可以使用dotwhisker::by_2sd

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM