![](/img/trans.png)
[英]How to plot multiple group means and the confidence intervals in ggplot2 (R)?
[英]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
是否可以使用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.