Box Plots
Data Visualization
The Five-Number Summary in One Powerful Diagram
A box plot compactly summarizes a distribution using the five-number summary and clearly shows outliers. It is one of the most powerful tools for comparing distributions across groups.
- Five-number summary — Min, Q1, median, Q3, max in one glance
- Outlier detection — Points beyond the whiskers are flagged instantly
- Group comparison — Side-by-side boxes reveal differences between populations
- Skewness indicator — Symmetric boxes mean symmetric data; lopsided boxes tell a different story
When you need to compare distributions quickly, nothing beats the box plot.
What You'll Learn
- 1Compute the five-number summary and the 1.5×IQR fences for a dataset
- 2Explain which convention drew the whiskers in a plot you are reading
- 3Diagnose skewness from the median line, the box and the whisker lengths
- 4Choose between box, violin and strip plots for a given sample size
What is a Box Plot?
Definition
A box plot (or box-and-whisker plot) compactly summarizes a distribution using the five-number summary and clearly shows outliers. It is one of the most powerful tools for comparing distributions across groups.
The Five-Number Summary
| Statistic | Symbol | Description |
|---|---|---|
| Minimum | Min | Smallest non-outlier value |
| First Quartile | Q1 | 25th percentile |
| Median | Q2 | 50th percentile |
| Third Quartile | Q3 | 75th percentile |
| Maximum | Max | Largest non-outlier value |
The box spans to — the middle half of the observations — and its width is the interquartile range. Half of the data sits inside the box by construction, so a narrow box means the centre of the distribution is tightly packed while a wide one means even the middle half is spread out. Everything outside the box is divided into two whisker regions, each holding a quarter of the data in a symmetric distribution.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import stats
np.random.seed(42)
# Dataset: salary data for three departments
data = {
'Engineering': np.random.normal(95000, 15000, 50),
'Marketing': np.random.normal(75000, 12000, 50),
'Operations': np.random.normal(65000, 10000, 50)
}
# Compute five-number summaries
print("Five-Number Summaries:")
print(f"{'Dept':<15} {'Min':>8} {'Q1':>8} {'Median':>8} {'Q3':>8} {'Max':>8} {'IQR':>8}")
print("-" * 65)
for dept, salaries in data.items():
q1, med, q3 = np.percentile(salaries, [25, 50, 75])
iqr = q3 - q1
# Whisker bounds (1.5 * IQR rule)
lower = q1 - 1.5 * iqr
upper = q3 + 1.5 * iqr
min_val = salaries[salaries >= lower].min()
max_val = salaries[salaries <= upper].max()
outliers = salaries[(salaries < lower) | (salaries > upper)]
print(f"{dept:<15} {min_val:>8,.0f} {q1:>8,.0f} {med:>8,.0f} {q3:>8,.0f} {max_val:>8,.0f} {iqr:>8,.0f}")
if len(outliers) > 0:
print(f" -> {len(outliers)} outlier(s): {[f'${o:,.0f}' for o in outliers]}")
Outlier Detection: The 1.5×IQR Rule
def detect_outliers(data):
q1, q3 = np.percentile(data, [25, 75])
iqr = q3 - q1
lower_fence = q1 - 1.5 * iqr
upper_fence = q3 + 1.5 * iqr
outliers = data[(data < lower_fence) | (data > upper_fence)]
return outliers, lower_fence, upper_fence
# Add some outliers to data
dept_data = np.concatenate([data['Engineering'], [200000, 25000]]) # two outliers
outliers, lower, upper = detect_outliers(dept_data)
print(f"Lower fence: ${lower:,.0f}")
print(f"Upper fence: ${upper:,.0f}")
print(f"Outliers found: {outliers}")
Two properties make this rule the default. Because quartiles are order statistics, contamination beyond the hinges cannot move the fences much, so the rule is stable on skewed data. And the multiplier 1.5 was chosen against the normal distribution: the fences land about 2.7 standard deviations out, which flags roughly one observation in several hundred in perfectly normal data — a useful rate, not a random one.
Which convention drew your whiskers?
There is no single standard, and two correct tools can produce different pictures of the same data.
| Convention | Whiskers reach | Points plotted beyond | Typical default in |
|---|---|---|---|
| Tukey 1.5×IQR | Furthest observation inside the fences | Yes, individually | matplotlib, seaborn, R boxplot |
| Min–max | Absolute minimum and maximum | Never | Simple range summaries |
| Percentile whiskers | e.g. 5th and 95th percentile | Yes, beyond those percentiles | Seaborn whis=[5, 95] |
| Notches | Median ± 1.58 × IQR / √n | n/a — the notch marks median uncertainty | showmeans and notched variants |
# The same data under three whisker conventions
sample = np.concatenate([np.random.normal(50, 8, 60), [88, 95]])
fig, axes = plt.subplots(1, 3, figsize=(14, 4), sharey=True)
for ax, whis, title in zip(axes, [1.5, [5, 95], 'range'],
['Tukey 1.5xIQR', '5th-95th percentile', 'Min-max (no outliers)']):
ax.boxplot(sample, whis=whis, patch_artist=True,
boxprops=dict(facecolor='lightblue'))
ax.set_title(title)
plt.tight_layout()
plt.savefig('whisker_conventions.png', dpi=150)
plt.show()
Reading a plot without knowing the convention invites misinterpretation: a point beyond a whisker is an outlier under Tukey's rule but merely beyond the 95th percentile under a percentile convention. Always check the tool's documentation before describing a point as anomalous.
Worked Example: Drawing the Box by Hand
Reading Skewness From the Box
Three visual cues encode shape, and each has a numeric counterpart you can compute:
- Median line inside the box. If it sits low in the box, the upper quarter of the middle half is stretched, which signals right skew. Its position as a fraction between and is the first check.
- Whisker length ratio. A longer upper whisker than lower whisker says the upper tail runs further, again right skew. Symmetric data has near-equal whiskers.
- Bowley skewness. The coefficient for the worked example above equals , confirming moderate right skew from order statistics alone.
For the same ten values the median sits one third of the way up the box, the upper whisker is 3 units long versus 3 for the lower one before trimming, and the outlier at 25 stretches the tail further. Had the data been symmetric, all three cues would point the same way — a median centred in the box, matched whiskers, and a skewness coefficient near zero.
💡Notches answer a comparison question
Comparing Groups: What to Look For
| Display | What it reveals | What it hides | Use when |
|---|---|---|---|
| Box plot | Five-number summary and flagged outliers | Sample size, modes, density | Many groups to compare at a glance |
| Box + swarm | Summary plus every observation | Nothing at small n, clutter at large n | n under about 50 and honesty matters |
| Violin plot | Full estimated density with a box inside | Exact individual values | Large n where shape matters more than ranks |
| Histogram | Binned density of one group | Individual values and comparability across groups | Exploring a single distribution |
fig, axes = plt.subplots(1, 3, figsize=(15, 6))
# 1. matplotlib basic box plot
df_long = pd.DataFrame({
'Salary': np.concatenate(list(data.values())),
'Department': np.repeat(list(data.keys()), 50)
})
axes[0].boxplot([data[d] for d in data.keys()],
labels=list(data.keys()),
patch_artist=True,
boxprops=dict(facecolor='lightblue', color='navy'),
medianprops=dict(color='red', linewidth=2),
flierprops=dict(marker='o', markerfacecolor='red', markersize=6))
axes[0].set_title('Department Salaries\n(Box Plot)')
axes[0].set_ylabel('Salary ($)')
axes[0].yaxis.set_major_formatter(plt.FuncFormatter(lambda x, p: f'${x/1000:.0f}K'))
# 2. Seaborn box plot (easier, prettier)
sns.boxplot(data=df_long, x='Department', y='Salary', ax=axes[1],
palette='Set2', width=0.5)
axes[1].set_title('Seaborn Box Plot')
axes[1].yaxis.set_major_formatter(plt.FuncFormatter(lambda x, p: f'${x/1000:.0f}K'))
# 3. Violin + Box (best of both worlds)
sns.violinplot(data=df_long, x='Department', y='Salary', ax=axes[2],
palette='Set3', inner='box')
axes[2].set_title('Violin + Box Plot\n(shows full distribution)')
axes[2].yaxis.set_major_formatter(plt.FuncFormatter(lambda x, p: f'${x/1000:.0f}K'))
plt.tight_layout()
plt.savefig('box_plots.png', dpi=150)
plt.show()
When judging groups, compare medians first, then overlap: boxes whose IQRs do not overlap suggest a difference in centre, while heavily overlapping boxes suggest the groups behave similarly regardless of a significant rank test. Remember that the box plot never shows how many observations produced it — a box built from six points looks identical to one built from six thousand — so add jittered points or state the sample size in the caption.
Reading a Box Plot
- Box width: spans IQR (middle 50% of data)
- Center line: median
- Whiskers: extend to furthest non-outlier within 1.5×IQR
- Points beyond whiskers: outliers (plotted individually)
Box Plots in Machine Learning
In ML, box plots are critical for:
| ML Use Case | What to Box Plot | What to Look For |
|---|---|---|
| Outlier detection | Each feature | Points beyond whiskers |
| Model comparison | Error metrics across folds | Consistency of performance |
| Data drift | Feature distributions train vs test | Shifted distributions |
| Residual analysis | Predicted vs actual errors | Symmetric spread |
| Class separation | Feature values by class | Non-overlapping boxes = good feature |
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score
from sklearn.datasets import make_regression
# Compare multiple models using box plots of cross-validation scores
from sklearn.linear_model import Ridge, Lasso, ElasticNet
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
X, y = make_regression(n_samples=500, n_features=10, noise=10, random_state=42)
models = {
'Linear': LinearRegression(),
'Ridge': Ridge(alpha=1.0),
'Lasso': Lasso(alpha=0.1),
'Random Forest': RandomForestRegressor(n_estimators=100, random_state=42),
'GBM': GradientBoostingRegressor(n_estimators=100, random_state=42)
}
cv_scores = {}
for name, model in models.items():
scores = cross_val_score(model, X, y, cv=5, scoring='r2')
cv_scores[name] = scores
print(f"{name:15s}: mean={scores.mean():.3f}, std={scores.std():.3f}")
# Box plot comparison
plt.figure(figsize=(10, 5))
plt.boxplot(cv_scores.values(), labels=cv_scores.keys())
plt.title('Model Comparison (5-Fold CV R² Scores)')
plt.ylabel('R² Score')
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
Five folds per model is a small sample, so the box in that comparison rests on five points: read it as a quick sanity check on spread rather than as a precise estimate of variability. For drift monitoring the box plot is more convincing, because comparing the interquartile range and median of a feature between the training window and the serving window detects shifts that a mean comparison misses entirely.
Frequently Asked Questions
Why does my box plot show no whiskers?
Every observation is either an outlier or the whiskers coincide with the box. Check the whisker convention first: under a percentile setting such as 5th to 95th the whiskers are short by construction, and with heavily tied data the quartiles may collapse onto the same value.
Is every point beyond a whisker a data error?
No. The rule is a geometric description, not a verdict. Under a normal model about one observation in several hundred falls outside, so in a sample of a thousand a handful of flagged points is expected behaviour — investigate them, do not delete them.
Why is the median not in the middle of the box?
Because the two quarters flanking it need not be equally wide. A median sitting low in the box with a long upper whisker is the classic signature of right-skewed data such as salaries or prices.
Can box plots compare groups with very different sample sizes?
They can, but the plot hides n, so a group of eight points and a group of eight thousand look equally authoritative. Add swarm or strip points, report n in the caption, or use notches so that median uncertainty scales with the sample size.
Common Mistakes
Assuming whiskers always reach the minimum and maximum
Fix: Check the convention: under Tukey's rule they stop at the furthest observation inside Q1 − 1.5×IQR and Q3 + 1.5×IQR, and the rest are plotted as points.
Reading a box plot without knowing the sample size
Fix: Box plots suppress n entirely — annotate it or overlay the raw points before drawing conclusions about two groups.
Treating every flagged point as an error to be deleted
Fix: The 1.5×IQR rule is a description of geometry; verify each point against its source record before removing anything.
Key Takeaways
- The box spans Q1 to Q3 with the median line inside, and each whisker reaches the furthest observation that stays within 1.5×IQR of the hinges
- Whisker conventions differ between tools — Tukey, min-max and percentile — so confirm which one produced the plot before calling a point an outlier
- Skewness reads off three cues: where the median sits in the box, which whisker is longer, and the Bowley coefficient (Q3 + Q1 − 2·median) / IQR
- Notches scale as 1.58 × IQR / √n and let you judge whether two medians differ without running a test
- Box plots hide sample size and multimodality, so pair them with raw points or a density view when either matters
Interview Questions
Q1: How do you construct a box plot?
Compute the five-number summary, draw the box from Q1 to Q3 with a line at the median, extend whiskers to the furthest observations within 1.5×IQR of the hinges, and plot anything beyond those fences individually.
Q2: What does the width of the box represent?
The interquartile range — the spread of the middle 50% of the data. Two groups with the same median but different box widths have the same centre but different typical dispersion.
Q3: A point sits just beyond the upper whisker. What do you do?
Confirm the whisker convention the tool used, then trace the value back to its source record. If it is real, keep it and report the summary with and without it rather than silently deleting it.
Q4: When would you choose a violin plot over a box plot?
When the sample is large enough for a density estimate to be reliable and the shape matters — bimodality in particular is invisible in a box plot, since the box only reports order statistics.