stat_compare_means() adds statistical comparison results to a ggplot2 graphic. With method = "t.test", it compares the means of the plotted groups and places the result at specified coordinates. section 7.4.1
A practical comparison workflow uses it alongside:
- Long-format data with one grouping variable and one measurement variable. section 7.4.1
- geom_boxplot() to show distributions and stat_summary() to mark group means. section 7.4.1
- label.x and label.y to position the test result inside the chart. section 7.4.1
Compare home and road foul calls
ggplot(temp1, aes(x = team, y = fouls, fill = team)) + geom_boxplot() + stat_summary(fun = mean, geom = "point", color = "white") + stat_compare_means(method = "t.test", label.x = 1.4, label.y = 34) section 7.4.1
temp1.text <- c("Home Team", "Road Team")
p1 <- ggplot(temp1, aes(x = team, y = fouls, fill = team)) +
geom_boxplot() +
labs(title = "Personal Foul Calls: Home vs. Road Teams",
subtitle = "2018-19 Regular Season",
x = "",
y = "Personal Fouls per Game") +
stat_summary(fun = mean, geom = "point", shape = 20, size = 8,
color = "white", fill = "white") +
theme(legend.position = "none") +
scale_x_discrete(labels = temp1.text) +
theme(plot.title = element_text(face = "bold")) +
stat_compare_means(method = "t.test",
label.x = 1.4, label.y = 34)
Browse the complete personal-foul visualization, including labels, styling, mean markers, and statistical annotation. section 7.4.1
