![](/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.