liveBook · Manning

Stat_compare_means() function

As explained in Statistics Slam Dunk

The stat_compare_means() function from ggpubr adds statistical comparison results, including p-values, to a ggplot2 graphic.

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

How Statistics Slam Dunk covers it

How deep it goes
Explains annotation, test method, and coordinate placement but does not detail implementation internals.
Examples
Uses paired NBA boxplots comparing personal fouls and free throw attempts for home and road teams.
What it assumes
Assumes basic ggplot2 mapping and data reshaping while demonstrating mean markers and test annotations.
What you can do after
Apply it via ggpubr to annotate ggplot2 comparisons with t-test results.
How it connects
Connects ggpubr to ggplot2, boxplots, stat_summary(), and independent t-tests.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Statistics Slam Dunk. The section links point to the parts of the book it draws on.