Box Plots
DS 2023 | Communicating with Data

Overview¶
A box plot is a way to display the summary statistics of a numeric feature.
It uses a minimalist geometric drawing composed of a set of glyphs — a rectangle (the “box”), perpendicular lines (the “whiskers”), and small circles — plotted along a line.
The line is metric, such that distance maps onto a numeric scale, and the position of the glyphs along the axis signifies their numeric values.
Because of its design, box plots are often called “box-and-whiskers” plots.
Using the symbolism of the image, a box plot represents the following statistics:
| Statistic | Location on box plot |
|---|---|
| Minimum value (min) | Far left whisker |
| First quartile (Q1) | Far left box border |
| Median value | Central line |
| Third quartile (Q3) | Far right box border |
| Maximum value (max) | Far right whisker |
| Interquartile range (IQR) | The box |
| Outliers | Dots to the left and right of Q1 and Q3 |
Use Cases¶
Box plots play a central role in exploratory data analysis (EDA).
They can quickly show how much a distribution varies from the normal.
They are also optimized for showing outliers — in fact, the minimum and maximum values represented by the outer whiskers are estimates of outlier thresholds.
Comparing many groups at once
This is the box plot’s principal advantage over both the histogram and the density plot.
A box plot occupies a single line, so twenty or fifty groups can be placed on one set of axes and still be read.
Twenty histograms require twenty panels. Twenty density curves on shared axes become an unreadable tangle.
Identifying outliers by an explicit rule
A histogram or a density plot leaves the identification of outliers to the reader’s judgment.
The box plot applies a stated rule, Tukey’s , and marks every point that falls outside it.
This makes the determination reproducible, and it makes it arguable, which is better than leaving it implicit.
Reading summary statistics off the plot
The median, the quartiles, and the interquartile range can be read directly from their positions on the axis.
Neither a histogram nor a density plot displays any of these quantities.
Robustness
The box plot is built from quantiles, which are resistant to extreme values.
Adding a single observation of 106 to a series moves the mean substantially and moves the median not at all. The box plot registers such a value as one outlier point rather than rescaling the whole display.
How outliers are computed¶
Each of the visual features of the box plot corresponds to a number based on the quantiles associated with a series. The order of computation is as follows:
Compute , the median, and , i.e. the first, second, and third quantiles.
These values may be computed by hand but are easily obtained by tools like Pandas’
.quantile()and.median()methods.
Compute the interquartile range :
.
Multiply the by a factor, which is usually 1.5 by Tukey’s rule:
Compute the and values:
Replace these values with the nearest actual data points that do not exceed the value.
Find outliers:
Creating a box plot from scratch¶
First, let’s create a function to compute the various stats required to construct a box plot from a series of numeric data.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
def compute_box_stats(S):
# Get the quartiles (which are quantiles at quarterly intervals)
Q1, Q2, Q3 = S.quantile([.25, .5, .75])
# Get the inter-quartile range
IQR = Q3 - Q1
# Apply Tukey's rule to compute outliers
tukey = IQR * 1.5
box_min = Q1 - tukey
box_max = Q3 + tukey
box_min_adj = S[S >= box_min].min() # Find nearest actually data point
box_max_adj = S[S <= box_max].max() # ditto
outliers = S[(S < box_min_adj) | (S > box_max_adj)].to_list()
# Return all the things as a Series
return pd.Series({
'Q1': Q1,
'median' : Q2,
'Q3': Q3,
'IQR': IQR,
'min': box_min_adj,
'max': box_max_adj,
'outliers': outliers
})Let’s try it out on the tips data set from Seaborn.
tips = sns.load_dataset('tips')
tips.head()tips_stats = compute_box_stats(tips.total_bill)
tips_statsQ1 13.3475
median 17.795
Q3 24.1275
IQR 10.78
min 3.07
max 40.17
outliers [48.27, 44.3, 41.19, 48.17, 50.81, 45.35, 40.5...
dtype: objectNow let’s create a function to draw the box plot.
We will use straight Matplotlib here, i.e. the functions plt.subplots() and plt.plot().
The colors of each part of different to highlight the constructed nature of the plot.
def box_plot(box_stats):
# Set the figure size
plt.figure(figsize=(10, 1))
# Draw the horizontal lines
plt.plot([box_stats['min'], box_stats['Q1']], [1, 1], c='red')
plt.plot([box_stats['Q3'], box_stats['max']], [1, 1], c='blue')
# Draw the vertical lines
for k in ['min', 'Q1', 'median', 'Q3', 'max']:
x = box_stats[k]
plt.plot([x, x], [.95, 1.05], c='green')
# Draw the box top and bottom
plt.plot([box_stats['Q1'], box_stats['Q3']], [.95, .95], c='purple')
plt.plot([box_stats['Q1'], box_stats['Q3']], [1.05, 1.05], c='orange')
# Draw the outliers
for ol in box_stats['outliers']:
plt.plot(ol, 1, c='turquoise', marker='o', alpha=.75)
# Clean up
sns.despine(left=True, bottom=True)
plt.yticks([])
plt.show()box_plot(tips_stats)
Using Pandas’ box plot function¶
Of course, Pandas can do all this for you and more.
Here is the simplest example.
tips.total_bill.plot.box()
plt.show()
We can make the plot horizontal by seting vert to False.
tips.total_bill.plot.box(vert=False)
plt.show()
We are of course also free to clean it up a bit. A single box plot doesn’t really need a bounding box.
tips.total_bill.plot.box(vert=False, figsize=(5, 2))
sns.despine(left=True, bottom=True)
plt.show()
Showing box plots by category¶
Let’s look at another data set to show how box plots for multiple series can be plotted on the same axes.
Here we use the healthexp data set from Seaborn which tracks health costs and outcomes for various countries from 1970 to 2020.
healthexp = sns.load_dataset('healthexp')
healthexp.head()To plot all of these at once, in order to compare them, we can set the by parameter to Country.
This implicitly groups the data by Country and then shows the respective box plots on a single axes.
healthexp.plot.box(column="Life_Expectancy", by="Country")
plt.show()
Here is how we can achieve the same effect using wide data.
life_exp_wide = healthexp.pivot(index='Year', columns='Country', values='Life_Expectancy')
life_exp_wide.head()life_exp_wide.plot.box()
plt.show()
A horizontal view is sometimes preferable when the number of box plots is large, given the constraint of page width.
life_exp_wide.plot.box(vert=False)
plt.show()
Now, we can use subplots to compare the categories, but since box plots are relatively compact, there is no real value gained by doing this.
In fact, it complicates things. You have to remove things to make the visualization clearer.
life_exp_wide.plot.box(subplots=True, figsize=(10,5), sharey=True)
sns.despine(left=True)
plt.show()
Sorting by median¶
Often, it is useful to sort the box plots to show ranking. It is common practice to sort by median.
Here is a way to do that.
life_exp_wide.median().sort_values().indexIndex(['USA', 'Germany', 'Great Britain', 'Canada', 'France', 'Japan'], dtype='str', name='Country')life_exp_wide[life_exp_wide.median().sort_values().index].plot.box(vert=False)
plt.show()
Sorting by category¶
Sometimes, the categories used to group box plots have a natural order.
This is true of the day feature in the tips data set.
You want these to display in order.
But look what happens when you ask Pandas’ to group the plots by day.
tips.plot.box(column='total_bill', by='day')
plt.show()
They display out of their natural order; instead, they are displayed in alphabetic order, which is not what we want.
This happens even though the data type associated with day in tips is Category, which preserves the correct order. However, the plot function does not honor this order.
The solution to this is to create a wide version of the data, i.e. we need to project the domain of day onto the column axis of a new data frame.
Because day is of type category, the pivot returns the columns in their defined order.
tips_wide = tips.pivot(columns='day', values='total_bill')
tips_wide.index.name = 'obs_id'
tips_wideNote the order of the days that order of days is what we want.
Now, we can pass the wide table to Pandas and it will do the right thing.
tips_wide.plot.box()
plt.show()
Change the properties of the box plot image¶
There are various properties of box plots that can be changed by passing values to the boxprops dictionary.
As always, consult the documentation to learn about all the properties that can be changed.
life_exp_wide[life_exp_wide.median().sort_values().index].plot.box(
vert=False,
boxprops={'linewidth': 2, 'color': 'orange'}
)
plt.show()
Combining box plots and histograms¶
Because box plots are minimalist in their design — which contributes to their usefulness — they are often complemented with histograms, so that the shape of the distribution can be viewed as well.
Here is one way to combine them.
ax = healthexp.Life_Expectancy.plot.hist()
ax2 = ax.twinx()
healthexp.Life_Expectancy.plot.box(ax=ax2, vert=False, color='tab:orange')
plt.show()
Another way is to juxtapose them vertically, using a horizontal box plot to match the x axis of the histogram.
fig, ax = plt.subplots(2, 1, height_ratios=[2, 1], sharex=True)
healthexp.Life_Expectancy.plot.hist(ax=ax[0])
healthexp.Life_Expectancy.plot.box(ax=ax[1], vert=False)
sns.despine(left=True, bottom=True)
plt.show()
- Lin, H., Zhang, R., & Tong, T. (2025). When Tukey Meets Chauvenet: A New Boxplot Criterion for Outlier Detection. Journal of Computational and Graphical Statistics, 35(1), 198–211. 10.1080/10618600.2025.2520577