I'd like to add results of a Tukey.HSD post-hoc test to a ggplot2
boxplot. This SO answer contains a manual example of what I want (i.e., the letters on the plot were added manually; groups which share a letter are indistinguishable, p>whatever).
Is there an automatic function add letters like these to a boxplot, based on AOV and Tukey HSD post-hoc analyis?
I think it would not be too hard to write such a function. It would look something like this:
set.seed(0)
lev <- gl(3, 10)
y <- c(rnorm(10), rnorm(10) + 0.1, rnorm(10) + 3)
d <- data.frame(lev=lev, y=y)
p_base <- ggplot(d, aes(x=lev, y=y)) + geom_boxplot()
a <- aov(y~lev, data=d)
tHSD <- TukeyHSD(a)
# Function to generate a data frame of factor levels and corresponding labels
generate_label_df <- function(HSD, factor_levels) {
comparisons <- rownames(HSD$l)
p.vals <- HSD$l[ , "p adj"]
## Somehow create a vector of letters
labels <- # A vector of letters, one for each factor level, generated using `comparisons` and `p.vals`
letter_df <- data.frame(lev=factor_levels, labels=labels)
letter_df
}
# Add the labels to the plot
p_base +
geom_text(data=generate_label_df(tHSD), aes(x=l, y=0, label=labels))
I realize that the TukeyHSD
object has a plot
method, and there is another package (which I can't now seem to find) which does what I'm describing in base graphics, but I would really prefer to do this in ggplot2
.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…