Overview
Sort the data and cut them into four equal parts. The box covers the middle half, from the first quartile to the third, with a line at the median. Its height is the interquartile range, a measure of spread that extreme values cannot stretch. A whisker runs from each end of the box to the furthest data point that is still within a set distance, usually 1.5 box heights. Anything beyond that is drawn as a separate point and called an outlier. The picture throws away the fine shape of the distribution on purpose, which is why a row of boxes is easy to compare.
A short history
John Tukey introduced the box and whisker plot around 1970 and made it widely known in his 1977 book Exploratory Data Analysis. He wanted a picture that could be drawn by hand from five numbers and that would not be distorted by a few extreme values. The rule of marking points beyond 1.5 times the interquartile range as outliers comes from the same book. The plot became a standard way to compare many groups side by side.
How it works
- Drop NaN entries and sort the values.
- Compute the first quartile, the median and the third quartile with the configured quantile rule.
- Compute the interquartile range, the third quartile minus the first.
- Set the fences: whisker times the interquartile range below the first quartile and above the third.
- End each whisker at the most extreme data point that lies inside the fences. The whisker ends are real data values, not the fences themselves.
- List every value outside the fences as an outlier.
- To draw, map values to vertical pixel positions and render one box per group as an SVG string.
Watch out for
- A box plot hides the shape inside the box. A sample with two separate peaks and a sample with one can draw the same box.
- On skewed data the 1.5 rule flags much of the long tail, because the fences assume a roughly symmetric bulk. Those points are not errors.
- Different quantile rules give slightly different quartiles on small samples, so two tools can draw different boxes from the same data.
- With very few values per group the quartiles are barely determined, and the box suggests a precision the data do not have.
- Setting show_outliers to false removes the outlier points from the picture and from the axis range, so the reader no longer sees them.
Use cases
When to use it
Comparing the centre, spread and outliers of several groups side by side, or getting the outlier fences of one column. For the full shape of a distribution a histogram or density estimate shows more.
In industry
- Manufacturing quality
- Engineers draw one box per production line or shift to see at a glance which line has a shifted median or a wider spread of part dimensions.
- Clinical research
- Trial reports use side by side box plots to compare a lab measurement across treatment arms and to show outlying patients.
- Web performance
- Operations teams compare response time distributions across server regions with box plots, since response times are skewed and have long tails.
Choosing it: what must hold
- A numeric variable, or an ordinal one with many levels, so that quartiles make sense.
- Enough observations per group, roughly a few dozen or more, for the quartiles to be stable.
- A goal of comparing centre, spread and outliers across groups, not of seeing the fine shape of one distribution.
When to choose something else
| If | Use instead |
|---|---|
| The distribution may have two or more peaks, which a box hides | A histogram or kernel density estimate from distribution analysis |
| Each group has only a handful of points | Plot the raw points as a strip or dot plot |
| You need the relationship between two numeric variables | A scatter plot |
Math foundations
Linear quantile
The default rule. It finds a position in the sorted data, counting from 1, and interpolates between the two neighbouring values. The quartiles are , and .
Interquartile range
The width of the middle half of the data, and the height of the box. Moving an extreme value further out does not change it.
Tukey's fences
The limits beyond which a value is called an outlier. The usual choice is .
Whisker ends
The whiskers stop at actual observations, the most extreme ones inside the fences. So a whisker can be much shorter than times the IQR.
Symbols
- the k-th smallest value of the sample
- number of values
- the quantile level, between 0 and 1
- position of the quantile in the sorted data, counted from 1
- first and third quartiles
- the whisker multiple (config whisker, default 1.5)
- lower and upper fence
Worked by hand
Ten values: 1, 2, 3, 4, 5, 6, 7, 8, 9, 100, with the linear rule and .
The value 100 lies above 14.5 and is an outlier. The upper whisker ends at 9 and the lower at 1, the most extreme values inside the fences.
Visual example
Loading the example.
Try this
- Drag the value at 88 toward the box and watch the moment it stops being an outlier and the whisker grows to reach it.
- Raise the whisker multiple w to 3: the fences move out and the outlier is absorbed.
- Drag a middle value past the median and see the box change shape while the far value stays flagged.
Code sample
from impl import BoxPlot
from config import BoxPlotConfig
plot = BoxPlot(BoxPlotConfig(whisker=1.5))
s = plot.stats([1, 2, 3, 4, 5, 6, 7, 8, 9, 100])
print(s["q1"], s["median"], s["q3"], s["outliers"]) # 3.25 5.5 7.75 [100.]
svg = plot.svg({"control": [1, 2, 3, 4, 5], "treated": [2, 4, 6, 8, 30]})
open("box.svg", "w").write(svg)Read the implementation (126 lines)
"""Box plots: the numbers a box-and-whisker plot is made of, and an SVG drawing of them.
NumPy and the standard library only. `stats` returns quartiles, whisker ends and outliers for one sample,
`svg` draws one vertical box per group and returns the picture as a string.
"""
from __future__ import annotations
from xml.sax.saxutils import escape
import numpy as np
try:
from .config import BoxPlotConfig
except ImportError: # run from the template's own folder
from config import BoxPlotConfig
_MARGIN_LEFT, _MARGIN_RIGHT, _MARGIN_TOP, _MARGIN_BOTTOM = 50.0, 15.0, 15.0, 35.0
class BoxPlot:
"""Computes box plot statistics (Tukey's rule) and renders them as SVG."""
def __init__(self, config: BoxPlotConfig | None = None) -> None:
self.config = config or BoxPlotConfig()
def stats(self, values) -> dict:
"""Box plot numbers for one sample.
values: array-like, shape (n,). NaN entries are dropped.
Returns a dict with q1, median, q3, iqr, lower_fence, upper_fence, whisker_low, whisker_high
(the most extreme data points still inside the fences), outliers (sorted array), mean and n.
"""
x = np.asarray(values, dtype=float).ravel()
x = np.sort(x[~np.isnan(x)])
if x.size == 0:
raise ValueError("values holds no numbers")
q1, median, q3 = (float(q) for q in np.quantile(x, [0.25, 0.5, 0.75], method=self.config.method))
iqr = q3 - q1
lower_fence = q1 - self.config.whisker * iqr
upper_fence = q3 + self.config.whisker * iqr
inside = x[(x >= lower_fence) & (x <= upper_fence)]
return {
"n": int(x.size),
"mean": float(x.mean()),
"q1": q1,
"median": median,
"q3": q3,
"iqr": iqr,
"lower_fence": lower_fence,
"upper_fence": upper_fence,
"whisker_low": float(inside.min()) if inside.size else q1,
"whisker_high": float(inside.max()) if inside.size else q3,
"outliers": x[(x < lower_fence) | (x > upper_fence)],
}
def group_stats(self, groups: dict) -> dict:
"""`stats` for every group. groups: {label: array-like of shape (n_i,)}."""
return {label: self.stats(values) for label, values in groups.items()}
def value_range(self, all_stats: dict) -> tuple[float, float]:
"""Lowest and highest value the picture must show, over all groups."""
lows = [s["whisker_low"] for s in all_stats.values()]
highs = [s["whisker_high"] for s in all_stats.values()]
if self.config.show_outliers:
for s in all_stats.values():
if s["outliers"].size:
lows.append(float(s["outliers"].min()))
highs.append(float(s["outliers"].max()))
lo, hi = min(lows), max(highs)
if hi == lo: # a flat sample still needs a range to draw in
lo, hi = lo - 0.5, hi + 0.5
return lo, hi
def y_pixel(self, value: float, lo: float, hi: float) -> float:
"""Vertical pixel position of `value` when the axis runs from lo (bottom) to hi (top)."""
plot_height = self.config.height - _MARGIN_TOP - _MARGIN_BOTTOM
return _MARGIN_TOP + (hi - value) / (hi - lo) * plot_height
def svg(self, groups: dict) -> str:
"""Draw one vertical box per group and return the SVG document as a string.
groups: {label: array-like of shape (n_i,)}. Each box spans q1 to q3, the inner line is the median,
the whiskers end at whisker_low and whisker_high, and outliers are circles.
"""
if not groups:
raise ValueError("groups is empty")
all_stats = self.group_stats(groups)
lo, hi = self.value_range(all_stats)
cfg = self.config
plot_width = cfg.width - _MARGIN_LEFT - _MARGIN_RIGHT
slot = plot_width / len(all_stats)
box_width = slot * 0.5
y = lambda v: self.y_pixel(v, lo, hi) # noqa: E731
parts = [
f'<svg xmlns="http://www.w3.org/2000/svg" width="{cfg.width}" height="{cfg.height}" '
f'viewBox="0 0 {cfg.width} {cfg.height}">',
f'<rect class="background" x="0" y="0" width="{cfg.width}" height="{cfg.height}" fill="white"/>',
f'<line class="axis" x1="{_MARGIN_LEFT}" y1="{_MARGIN_TOP}" x2="{_MARGIN_LEFT}" '
f'y2="{cfg.height - _MARGIN_BOTTOM}" stroke="black"/>',
f'<text class="tick" x="{_MARGIN_LEFT - 5}" y="{y(hi) + 4:.2f}" text-anchor="end" font-size="11">{hi:g}</text>',
f'<text class="tick" x="{_MARGIN_LEFT - 5}" y="{y(lo) + 4:.2f}" text-anchor="end" font-size="11">{lo:g}</text>',
]
for index, (label, s) in enumerate(all_stats.items()):
centre = _MARGIN_LEFT + slot * (index + 0.5)
left = centre - box_width / 2
parts.append(
f'<line class="whisker" x1="{centre:.2f}" y1="{y(s["whisker_high"]):.2f}" x2="{centre:.2f}" '
f'y2="{y(s["whisker_low"]):.2f}" stroke="black"/>'
)
parts.append(
f'<rect class="box" x="{left:.2f}" y="{y(s["q3"]):.4f}" width="{box_width:.2f}" '
f'height="{y(s["q1"]) - y(s["q3"]):.4f}" fill="#9ecae1" stroke="black"/>'
)
parts.append(
f'<line class="median" x1="{left:.2f}" y1="{y(s["median"]):.4f}" x2="{left + box_width:.2f}" '
f'y2="{y(s["median"]):.4f}" stroke="black" stroke-width="2"/>'
)
if cfg.show_outliers:
for value in s["outliers"]:
parts.append(f'<circle class="outlier" cx="{centre:.2f}" cy="{y(float(value)):.2f}" r="3" fill="none" stroke="black"/>')
parts.append(
f'<text class="label" x="{centre:.2f}" y="{cfg.height - _MARGIN_BOTTOM + 18}" text-anchor="middle" '
f'font-size="12">{escape(str(label))}</text>'
)
parts.append("</svg>")
return "\n".join(parts)- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 8, run with
python3 -m unittest -v
Practice
Call BoxPlot().stats on the ten values of the worked example and check every number. Then build BoxPlot objects with whisker set to 3.0 and with method set to weibull, and note which of q1, q3, the fences and the outliers change. Finish by calling svg on two groups and opening the result in a browser.
Check on learning
- Replace the value 100 by 1000 in the worked example. Which of the box plot numbers change, and what does that say about why the box is built from quartiles?
A way to think about it
Check whether the positions or the values around them move. Then compare with what the mean and the standard deviation would do.
- Two groups draw identical boxes. Give two very different samples that would produce that, and say which chart would separate them.
A way to think about it
The box fixes only five numbers. Think of one sample bunched in the middle of the box and one bunched at its two edges.
- Incomes are strongly right-skewed. Why does the 1.5 rule flag many high incomes, and what could you do before plotting so the rule behaves?
A way to think about it
The fences are symmetric around the box but the data are not. Consider what a log transform does to the distances in the upper tail.
- Why do the whiskers end at data points and not at the fences, and how would the plot mislead if they were drawn to the fences?
A way to think about it
Imagine a sample whose largest value sits just above . A whisker drawn out to would claim data in a region that is empty.