ggstatsplot
ggstatsplot draws a ggplot2 figure and runs the matching test in the same call. The subtitle carries the test statistic, the p-value, the effect size with its confidence interval, and the sample size. The caption carries a Bayes factor. The examples run in ggstatsplot 1.0.0.
The expression table has 30 samples in each of three treatment arms. The penguin table is the palmerpenguins data with incomplete rows removed.
The penguin measurements come from Kristen Gorman and Palmer Station LTER through the palmerpenguins package by Allison Horst, Alison Hill, and Kristen Gorman. The package explicitly identifies the data as CC0. This lesson removes incomplete rows and derives its plots and statistics from the remaining observations.
library(ggstatsplot)library(ggplot2)library(dplyr)
set.seed(42)dir.create("outputs", showWarnings = FALSE)
experiment <- tibble( sample_id = sprintf("S%02d", 1:90), group = factor(rep(c("Control", "Drug_A", "Drug_B"), each = 30)), log2_cpm = c(rnorm(30, 10, 2), rnorm(30, 13, 2.5), rnorm(30, 11.5, 2)))
penguins_clean <- palmerpenguins::penguins |> tidyr::drop_na()nrow(penguins_clean)[1] 333Do not name the measured column expression. ggstatsplot 1.0.0 builds an internal column
with that name, and the call stops with the error Names must be unique.
R 4.5 added its own penguins data set to the datasets package, with short column names
such as flipper_len. The palmerpenguins:: prefix keeps the flipper_length_mm names used
below.
Compare independent groups
Section titled “Compare independent groups”ggbetweenstats() draws a violin, a box, and the points for each group. It runs a Welch
one-way ANOVA, then Games-Howell pairwise tests with Holm-adjusted p-values.
pairwise.display = "all" shows every pair, not only the significant ones.
set.seed(42)between_plot <- ggbetweenstats( data = experiment, x = group, y = log2_cpm, type = "parametric", pairwise.display = "all", p.adjust.method = "holm", xlab = "Treatment", ylab = "Expression, log2 CPM")
ggsave( "outputs/ggstatsplot-betweenstats.png", between_plot, width = 8, height = 6.5, dpi = 150, bg = "white")
pairwise.display replaced the pairwise.comparisons = TRUE argument of older releases. The
old argument now falls into ... without an error and has no effect.
type picks the test family for independent groups.
type |
Overall test | Pairwise test |
|---|---|---|
"parametric" |
Welch one-way ANOVA | Games-Howell |
"nonparametric" |
Kruskal-Wallis | Dunn |
"robust" |
One-way ANOVA on trimmed means | Yuen’s trimmed means test |
"bayes" |
Bayesian ANOVA | Bayesian t-test |
Get the numbers as a table
Section titled “Get the numbers as a table”extract_stats() returns the tests behind the figure as tibbles, ready for a results table.
The pairwise table holds one row per pair.
between_stats <- extract_stats(between_plot)between_stats$pairwise_comparisons_data |> select(group1, group2, statistic, p.value, test, p.adjust.method)# A tibble: 3 × 6 group1 group2 statistic p.value test p.adjust.method <chr> <chr> <dbl> <dbl> <chr> <chr>1 Control Drug_A 5.46 0.00251 Games-Howell Holm2 Control Drug_B 4.57 0.0124 Games-Howell Holm3 Drug_A Drug_B -2.06 0.320 Games-Howell HolmCompare repeated measures
Section titled “Compare repeated measures”ggwithinstats() expects one row per subject and time point. Pass the subject column to
subject.id, so the pairing does not depend on the row order. The parametric version runs a
repeated measures ANOVA with a sphericity correction, then paired t-tests, and a line joins
the group means.
set.seed(42)tumor <- tibble( patient = rep(sprintf("P%02d", 1:20), times = 3), time = factor( rep(c("Baseline", "Month3", "Month6"), each = 20), levels = c("Baseline", "Month3", "Month6") ), tumor_mm = c(rnorm(20, 50, 10), rnorm(20, 42, 9), rnorm(20, 36, 8)))
within_plot <- ggwithinstats( data = tumor, x = time, y = tumor_mm, subject.id = patient, type = "parametric", pairwise.display = "all", xlab = "Visit", ylab = "Tumor diameter, mm")
ggsave( "outputs/ggstatsplot-withinstats.png", within_plot, width = 8, height = 6.5, dpi = 150, bg = "white")
One sample against a reference value
Section titled “One sample against a reference value”gghistostats() tests whether the mean differs from test.value. The dashed line marks the
sample mean.
set.seed(42)histo_plot <- gghistostats( data = experiment, x = log2_cpm, test.value = 12, type = "parametric", binwidth = 0.75, xlab = "Expression, log2 CPM")
ggsave( "outputs/ggstatsplot-histostats.png", histo_plot, width = 8, height = 5.5, dpi = 150, bg = "white")
Correlation with marginal histograms
Section titled “Correlation with marginal histograms”ggscatterstats() fits a line, prints Pearson’s r with its confidence interval, and adds a
histogram of each variable on the margins. The margins come from the ggside package; set
marginal = FALSE to drop them.
set.seed(42)scatter_plot <- ggscatterstats( data = penguins_clean, x = flipper_length_mm, y = body_mass_g, type = "parametric", xlab = "Flipper length, mm", ylab = "Body mass, g")
ggsave( "outputs/ggstatsplot-scatterstats.png", scatter_plot, width = 8, height = 6.5, dpi = 150, bg = "white")
Correlation matrix
Section titled “Correlation matrix”ggcorrmat() shows every pairwise correlation. A cross marks a correlation that is not
significant after the Holm adjustment. All six penguin correlations pass, so no cell carries a
cross here.
corr_plot <- ggcorrmat( data = penguins_clean, cor.vars = c( bill_length_mm, bill_depth_mm, flipper_length_mm, body_mass_g ), type = "parametric")
ggsave( "outputs/ggstatsplot-corrmat.png", corr_plot, width = 7, height = 6.5, dpi = 150, bg = "white")
Two categorical variables
Section titled “Two categorical variables”ggbarstats() stacks the proportions of x within each level of y and runs a chi-square
test of independence. The labels above the bars test each level of y against equal
proportions.
set.seed(42)bar_plot <- ggbarstats( data = penguins_clean, x = species, y = island)
ggsave( "outputs/ggstatsplot-barstats.png", bar_plot, width = 8, height = 6.5, dpi = 150, bg = "white")
One categorical variable
Section titled “One categorical variable”ggpiestats() with only x runs a goodness-of-fit chi-square test against equal
proportions.
set.seed(42)pie_plot <- ggpiestats( data = penguins_clean, x = species)
ggsave( "outputs/ggstatsplot-piestats.png", pie_plot, width = 7, height = 6, dpi = 150, bg = "white")
Regression coefficients
Section titled “Regression coefficients”ggcoefstats() takes a fitted model and draws each estimate with its 95% confidence interval,
its t statistic, and its p-value. It reads lm, glm, mixed models, and most other model
classes.
model <- lm( body_mass_g ~ flipper_length_mm + bill_length_mm + bill_depth_mm + species, data = penguins_clean)
coef_plot <- ggcoefstats(model)
ggsave( "outputs/ggstatsplot-coefstats.png", coef_plot, width = 8, height = 6, dpi = 150, bg = "white")
Repeat a plot for each subgroup
Section titled “Repeat a plot for each subgroup”Every gg*stats() function has a grouped_ version that splits the data by grouping.var
and combines the panels. Here two species each get their own comparison of body mass by sex.
droplevels() removes the empty Chinstrap level after the filter. Each subtitle needs about
7 inches of width, so size the saved figure to the number of panels.
two_species <- penguins_clean |> filter(species != "Chinstrap") |> droplevels()
set.seed(42)grouped_plot <- grouped_ggbetweenstats( data = two_species, x = sex, y = body_mass_g, grouping.var = species, ylab = "Body mass, g", plotgrid.args = list(nrow = 1))
ggsave( "outputs/ggstatsplot-grouped.png", grouped_plot, width = 15, height = 6.5, dpi = 150, bg = "white")
Common arguments
Section titled “Common arguments”| Argument | Values | Effect |
|---|---|---|
type |
"parametric", "nonparametric", "robust", "bayes" |
Test family |
pairwise.display |
"significant", "non-significant", "all", "none" |
Which pairs get a bracket |
p.adjust.method |
"holm", "bonferroni", "BH", "none" |
Multiple comparison correction |
subject.id |
A column | Pairs repeated measures in ggwithinstats() |
bf.message |
TRUE, FALSE |
Bayes factor caption |
results.subtitle |
TRUE, FALSE |
Statistics subtitle |
centrality.plotting |
TRUE, FALSE |
Mean or median label on each group |
ggplot.component |
A list of ggplot2 layers | Extra scales or theme settings |
ggstatsplot fixes some defaults on purpose. Parametric comparisons of independent groups always use Welch’s test, and effect sizes are always the unbiased versions, Hedges’ g and omega squared. Call the statsExpressions package directly when you need a different choice.
ggstatsplot or ggpubr
Section titled “ggstatsplot or ggpubr”| Need | ggstatsplot | ggpubr |
|---|---|---|
| Statistics on the figure | Full subtitle, automatic | p-values and stars |
| Effect size and confidence interval | Automatic | Not shown |
| Bayes factor | Caption | Not available |
| Control over the look | Through ggplot.component and + |
Full ggplot2 control |
| Typical use | Exploration and supplementary figures | Main figures with a fixed style |
See also
Section titled “See also”- ggstatsplot, the Test on the Plot walks through the same functions with the reasoning behind each test.
- Multiple Groups: ANOVA and Kruskal-Wallis explains the overall tests and the post hoc comparisons.
- Correlation and
Categorical Data: Chi-square and Fisher cover
the tests behind
ggscatterstats(),ggcorrmat(), andggbarstats(). - Mixed-Effects and Repeated Measures models repeated measures when a repeated measures ANOVA is too rigid.
- The ggpubr cheatsheet adds p-values to plots you style yourself.
Scientific references
Section titled “Scientific references”Patil, 2021 describes the ggstatsplot approach, which adds the details of a statistical test to its plot.
Horst, Hill, and Gorman, 2020 publish the Palmer Archipelago penguin data in the palmerpenguins package.
Further reading
Section titled “Further reading”The between-group reference defines the test families, pairwise display, and adjustment arguments. The within-subject reference explains the subject identifier and the expected arrangement of repeated observations.
The statistics extraction reference identifies the tables behind the subtitle, caption, and pairwise comparisons. Use those tables to report a test without transcribing a figure label. The palmerpenguins README identifies the penguin measurements, original study, and data terms.