Box Plots
A box plot (box-and-whisker plot) summarises a numeric variable with five numbers and shows outliers individually. It takes very little space, which makes it ideal for comparing several groups side by side.
The five-number summary
| Part of the plot | Value |
|---|---|
| bottom of the box | first quartile Q1 (25% of values are below it) |
| line inside the box | median (Q2, 50%) |
| top of the box | third quartile Q3 (75%) |
| whiskers | reach to the most extreme values that are not outliers |
| dots beyond the whiskers | outliers |
The box therefore holds the middle 50% of the data, and its height is the interquartile range IQR = Q3 − Q1. By the most common convention (Tukey's), a value is an outlier if it is more than 1.5 × IQR below Q1 or above Q3. You will compute these in detail in Quartiles and Percentiles and Interquartile Range.
Computing the pieces
Using the commute times of the 40 employees again:
import numpy as np
commute = np.array([22, 35, 18, 41, 27, 30, 25, 52, 33, 29, 19, 24, 38, 31, 27, 45, 23, 28, 36, 26,
21, 34, 30, 58, 27, 32, 25, 29, 40, 24, 17, 31, 28, 37, 26, 33, 22, 30, 47, 28])
q1, median, q3 = np.percentile(commute, [25, 50, 75])
iqr = q3 - q1
low_fence, high_fence = q1 - 1.5 * iqr, q3 + 1.5 * iqr
print(f"Q1 = {q1}, median = {median}, Q3 = {q3}, IQR = {iqr}")
print(f"fences: {low_fence} and {high_fence}")
inside = commute[(commute >= low_fence) & (commute <= high_fence)]
print("whiskers end at:", inside.min(), "and", inside.max())
print("outliers:", commute[(commute < low_fence) | (commute > high_fence)])Q1 = 25.0, median = 29.0, Q3 = 34.25, IQR = 9.25
fences: 11.125 and 48.125
whiskers end at: 17 and 47
outliers: [52 58]
Drawing the box plot
import matplotlib.pyplot as plt
commute = [22, 35, 18, 41, 27, 30, 25, 52, 33, 29, 19, 24, 38, 31, 27, 45, 23, 28, 36, 26,
21, 34, 30, 58, 27, 32, 25, 29, 40, 24, 17, 31, 28, 37, 26, 33, 22, 30, 47, 28]
fig, ax = plt.subplots(figsize=(6, 2.5))
result = ax.boxplot(commute, vert=False, widths=0.5, patch_artist=True,
boxprops={"facecolor": "#cde2fb", "edgecolor": "#2a78d6"},
medianprops={"color": "#2a78d6", "linewidth": 2})
ax.set_xlabel("commute time (minutes)")
ax.set_yticks([])
plt.tight_layout()
plt.show()
print("outliers drawn as dots:", [int(v) for v in result["fliers"][0].get_xdata()])outliers drawn as dots: [52, 58]
The median line sits a bit left of the centre of the box, the right whisker is longer than the left, and the outliers are on the right: three signs of a right-skewed distribution.
Comparing groups
Box plots shine when you put several groups next to each other. Here we simulate delivery times (minutes) for three couriers:
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(21)
couriers = {
"Rapid": rng.normal(32, 4, 60),
"Steady": rng.normal(38, 2, 60),
"Wildcard": rng.normal(35, 10, 60),
}
fig, ax = plt.subplots(figsize=(6, 3.5))
ax.boxplot(list(couriers.values()), widths=0.5)
ax.set_xticks([1, 2, 3], list(couriers.keys()))
ax.set_ylabel("delivery time (minutes)")
plt.tight_layout()
plt.show()
for name, t in couriers.items():
q1, med, q3 = np.percentile(t, [25, 50, 75])
print(f"{name:8s} median={med:5.1f} IQR={q3 - q1:5.1f}")Rapid median= 32.2 IQR= 6.5
Steady median= 37.9 IQR= 2.4
Wildcard median= 33.1 IQR= 12.3
"Rapid" is fastest on average, "Steady" is slower but very predictable (narrow box), and "Wildcard" is all over the place (wide box). The box plot shows both the centre and the reliability in one picture.
pandas shortcut
With data in a "long" table (one row per observation, a column for the group), pandas draws grouped box plots directly:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({
"shift": ["early"] * 6 + ["late"] * 6,
"units": [48, 52, 50, 47, 55, 51, 40, 58, 44, 61, 39, 57],
})
df.boxplot(column="units", by="shift", grid=False, figsize=(5, 3.5))
plt.suptitle("")
plt.title("Units produced per shift")
plt.tight_layout()
plt.show()
print(df.groupby("shift")["units"].describe()[["min", "25%", "50%", "75%", "max"]]) min 25% 50% 75% max
shift
early 47.0 48.5 50.5 51.75 55.0
late 39.0 41.0 50.5 57.75 61.0
Both shifts have the same median (50.5 units), yet the late shift's box is about five times taller: its output is far less consistent.
Note: Different programs compute quartiles in slightly different ways, so a box plot drawn elsewhere may show slightly different box edges for small datasets. The overall picture is the same.
Test yourself
What does the box (from bottom to top edge) of a box plot contain?
- All the data
- The middle 50% of the data
- Values within one standard deviation of the mean
- Only the outliers
Q1 = 20 and Q3 = 30. Using the 1.5 × IQR rule, which value is an outlier?
- 12
- 38
- 46
- 6
Two groups have the same median, but group B's box is three times wider. What does that tell you?
- Group B has a higher average
- Group B's values are much more spread out
- Group B has more observations
- Group B has no outliers