簡體   English   中英

如何用ggplot()繪制glht()置信區間?

[英]How to plot glht() confidence intervals with ggplot()?

使用multcomp包中的glht() ,可以計算出不同處理的置信區間,例如( source ):

Simultaneous Confidence Intervals

Multiple Comparisons of Means: Tukey Contrasts

Fit: lm(formula = Years ~ Attr, data = MockJury)

Quantile = 2.3749

95% family-wise confidence level
Linear Hypotheses:
                                Estimate  lwr       upr
Average - Beautiful ==      0   -0.3596   -2.2968   1.5775
Unattractive - Beautiful == 0    1.4775   -0.4729   3.4278
Unattractive - Average ==   0    1.8371   -0.1257   3.7999

然后可以使用plot()可視化這些間隔: 置信區間圖

是否可以使用ggplot()繪制這些間隔(以保持一致性和美觀性)? 如果是這樣,怎么辦?

如果沒有,是否有解決方法可以使輸出類似於ggplot()圖表?

如果將confint的輸出轉換為數據幀,則可以直接在ggplot2中繪制輸出。 下面是一個方法(使用glht使用該從幫助文件的例子) tidy函數從broom轉換confint()輸出到適合於繪制的數據幀:

library(multcomp)
library(tidyverse)
library(broom)

lmod <- lm(Fertility ~ ., data = swiss)

m = glht(lmod, linfct = c("Agriculture = 0",
                          "Examination = 0",
                          "Education = 0",
                          "Catholic = 0",
                          "Infant.Mortality = 0"))

confint(m) %>% 
  tidy %>% 
  ggplot(aes(lhs, y=estimate, ymin=conf.low, ymax=conf.high)) +
    geom_hline(yintercept=0, linetype="11", colour="grey60") +
    geom_errorbar(width=0.1) + 
    geom_point() +
    coord_flip() +
    theme_classic()

在此處輸入圖片說明

更新:為了回應評論...

置信區間的彎曲端

我不確定向誤差線添加彎曲末端的簡便方法,因為您可以通過使用geom_segment和帶有淺箭頭角的箭頭來接近。

confint(m) %>% 
  tidy %>% 
  ggplot(aes(x=lhs, y=estimate)) +
  geom_hline(yintercept=0, linetype="11", colour="grey60") +
  geom_segment(aes(xend=lhs, y=conf.low, yend=conf.high), size=0.4, 
               arrow=arrow(ends="both", length=unit(0.05, "inches"), angle=70)) + 
  geom_point() +
  coord_flip() +
  theme_classic()

在此處輸入圖片說明

lhs訂購

在排序方面, lhs將按字母順序排序,除非將其轉換為具有特定順序的因子。 例如,下面我們按estimate值排序。

confint(m) %>% 
  tidy %>% 
  arrange(estimate) %>% 
  mutate(lhs = factor(lhs, levels=unique(lhs))) %>%   # unique() returns values in the order they first appear in the data
  ggplot(aes(x=lhs, y=estimate)) +
  geom_hline(yintercept=0, linetype="11", colour="grey60") +
  geom_segment(aes(xend=lhs, y=conf.low, yend=conf.high), size=0.4, 
               arrow=arrow(ends="both", length=unit(0.05, "inches"), angle=70)) + 
  geom_point() +
  coord_flip() +
  theme_classic()

在此處輸入圖片說明

暫無
暫無

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

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