Using glht()
from the multcomp
package, one can calculate the confidence intervals of different treatments, like so ( 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
These intervals can then be visualized using plot()
:
Is it possible to plot these intervals using ggplot()
(for consistency and aesthetics)? If so, how?
If not, is there a workaround to make the output resemble a ggplot()
chart?
If you convert the output of confint
to a data frame, then you can directly plot the output in ggplot2. Here's an approach (using a glht
example from the help file) that uses the tidy
function from broom
to convert confint()
output to a data frame suitable for plotting:
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()
UPDATE: In response to the comment...
Curved ends for the confidence intervals
I'm not sure of an easy way to add curved ends to the errorbars, by you can come close by using geom_segment
and arrows with a shallow arrowhead angle.
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
ordering
In terms of ordering, lhs
will be ordered alphabetically unless it is converted to a factor with a specific order. For example, below we order by the value of 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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.