
25 Grouped box plots
theme_oregontrail()
Graphs in this chapter use ggrewindr::theme_oregontrail(), modeled on The Oregon Trail on an Apple II emulator: a gray window frame, a black screen, phosphor green text and marks in three shades, and a Fira Mono title.
25.1 Description
Grouped box plots display five different statistical measures across a series of categories, or groups, of a categorical variable.
The five statistical measures are 1) the first quartile, 2) the second quartile, and 3) the third quartile. The fourth and fifth values are the largest/smallest values no further than 1.5 X inter-quartile range from the hinges.
25.2 Set up
PACKAGES
Install packages.
show/hide
library(ggplot2)
library(dplyr) # for tibble() and data manipulationDATA
In The Oregon Trail, you picked a profession before you set out, and it decided how much money (and how many supplies) your party started with. We’ll simulate how many days it took 100 parties of each profession to reach Oregon. Each profession gets its own typical trip length (median_days), and rlnorm() draws each trip from a log normal distribution, so a few unlucky parties (dysentery, broken axles, lost oxen) take much longer than the rest. Setting the seed with set.seed() means you’ll get the same 300 trips every time you run the code below.
show/hide
set.seed(1985) # same 300 parties every time the code runs
oregon_trail <- tibble(
party_id = 1:300, # 300 different wagon parties, one row each
profession = rep(c("Banker", "Carpenter", "Farmer"), each = 100) # 100 parties per profession
) |>
mutate(
profession = factor(profession,
levels = c("Banker", "Carpenter", "Farmer")), # fastest to slowest
median_days = c(Banker = 140, Carpenter = 155, # typical days on the trail
Farmer = 170)[as.character(profession)], # (looked up for each profession)
days_to_oregon = round(
rlnorm(n(), meanlog = log(median_days), # trips cluster near the median
sdlog = 0.2) # with a longer tail of slow trips
)
) |>
select(party_id, profession, days_to_oregon)
glimpse(oregon_trail)
#> Rows: 300
#> Columns: 3
#> $ party_id <int> 1, 2, 3, 4, 5, 6, 7, 8, 9…
#> $ profession <fct> Banker, Banker, Banker, B…
#> $ days_to_oregon <dbl> 152, 112, 131, 144, 180, …25.3 Distribution
Grouped box plots compare five summary numbers across groups. When the data are skewed, those five numbers aren’t evenly spaced: the median sits closer to the bottom of the box, and the upper whisker is longer than the lower one. With only 100 trips per profession, sampling noise can hide this, so not every box below looks this way. Below we’ll move from the trips, to a picture, to the formula.
COUNT IT
Start with the first eight trips (all bankers).
show/hide
head(oregon_trail$days_to_oregon, 8)
#> [1] 152 112 131 144 180 126 164 179These trips took between 112 and 180 days. The summary below shows each profession’s quartiles. Only for bankers is the distance from the median up to the third quartile (upper_gap) larger than the distance down to the first quartile (lower_gap). For carpenters and farmers, the distance down is about the same or larger.
show/hide
oregon_trail |>
group_by(profession) |>
summarise(q1 = quantile(days_to_oregon, 0.25),
median = median(days_to_oregon),
q3 = quantile(days_to_oregon, 0.75)) |>
mutate(lower_gap = median - q1, upper_gap = q3 - median)DRAW IT
The box plots on the left use days. The bankers’ box is lopsided: the median line sits low in the box, and the long trips stretch the upper whisker. The farmers’ box leans the other way: the median sits high and the lower whisker is longer. The farmers also have a few outliers above the rest. The box plots on the right put the same trips on a log scale with scale_y_log10(). The log scale doesn’t make every box symmetric: 100 simulated trips are too few to match the formula, and the bankers and farmers each still have one low outlier.
show/hide
ggplot(oregon_trail, aes(x = profession, y = days_to_oregon,
fill = profession)) +
geom_boxplot(alpha = 2/3, show.legend = FALSE) +
labs(title = "Days", x = NULL, y = "Days to reach Oregon")
ggplot(oregon_trail, aes(x = profession, y = days_to_oregon,
fill = profession)) +
geom_boxplot(alpha = 2/3, show.legend = FALSE) +
scale_y_log10() +
labs(title = "Log scale", x = NULL, y = "Days (log10 scale)")

NAME IT
Each profession’s trips come from a log normal distribution, like the Microdrive photo sizes in Chapter 7:
\[ \log(X_{\text{profession}}) \sim \text{Normal}(\log(m_{\text{profession}}), \; \sigma = 0.2), \quad m = (140, 155, 170) \]
On the log scale, the quartiles sit \(0.674\,\sigma\) above and below the center, which is why the formula’s boxes are symmetric on the log scale. Back on the day scale, those quartiles become \(m\,e^{-0.674 \times 0.2}\) and \(m\,e^{0.674 \times 0.2}\): for bankers, about 122 and 160 days. That’s 18 days below the median but 20 days above it, and the gap grows the further out you go, which is why the formula stretches the upper whiskers. Try a larger sdlog in rlnorm() and the boxes become even more lopsided.
25.4 Grammar
CODE
Create labels with
labs()Initialize the graph with
ggplot()and providedataMap
professionto thexaxis and tofillMap
days_to_oregonto theyaxisAdd
geom_boxplot()and set thealphato2/3Set
outlier.shape = NA(so the outliers aren’t drawn twice)Add each trip as a point with
geom_jitter()Remove the legend with
show.legend = FALSE
show/hide
labs_grp_boxplots <- labs(
title = "The Oregon Trail",
caption = "Simulated data",
subtitle = "Days for 100 parties of each profession to reach Oregon",
x = "Profession", fill = "Profession",
y = "Days to reach Oregon")
ggp2_grp_boxplots <- ggplot(data = oregon_trail,
aes(x = profession,
y = days_to_oregon,
fill = profession)) +
geom_boxplot(alpha = 2/3,
outlier.shape = NA,
show.legend = FALSE) +
geom_jitter(width = 0.15, height = 0, alpha = 0.4,
show.legend = FALSE)
ggp2_grp_boxplots +
labs_grp_boxplotsGRAPH
When a categorical variable is supplied, the plot will contain a box for each level or group. Each point is one trip, jittered left and right so the points don’t overlap (height = 0 keeps each trip at its true number of days).

25.5 More info
25.5.1 Notches
Add notches to the box plot using the notch = TRUE and notchwidth arguments.1
show/hide
ggp2_grp_box_notch <- ggplot(data = oregon_trail,
aes(x = profession,
y = days_to_oregon,
fill = profession)) +
geom_boxplot(
notch = TRUE,
notchwidth = 0.85,
alpha = 2/3,
show.legend = FALSE)
ggp2_grp_box_notch +
labs_grp_boxplots
25.5.2 Outliers
Box plots display outliers using points, and we can change the color of these using the outlier.colour argument. Inside the geom_boxplot(), we map profession to color and set outlier.colour to NULL (so the outlier points take the mapped color):
show/hide
ggp2_grp_box_outliers <- ggplot(data = oregon_trail,
aes(x = profession,
y = days_to_oregon,
fill = profession)) +
geom_boxplot(aes(color = profession),
outlier.colour = NULL,
outlier.size = 2,
notch = TRUE,
notchwidth = 0.85,
alpha = 2/3,
show.legend = FALSE)
ggp2_grp_box_outliers +
labs_grp_boxplots
Each notch spans the median ± 1.58 × IQR / √n, a rough confidence interval for the median, and
notchwidthsets how narrow the notch is compared to the box.↩︎