如何使用 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 示例),它使用 broom 中的 tidy 函数将 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()