Box Plots in Matplotlib

Make box plots with plt.boxplot(), then label and color the boxes, flip them, show means and points, and group them.

To make a box plot in Matplotlib, pass a list of datasets to plt.boxplot() or ax.boxplot(); each dataset becomes one box. Name the boxes with tick_labels, and set patch_artist=True to fill them with color.

Quick Example

The sample data is exam scores for four classes.

import matplotlib.pyplot as plt
import numpy as np

rng = np.random.default_rng(14)
labels = ["Class A", "Class B", "Class C", "Class D"]
scores = [
    rng.normal(72, 8, 60),
    rng.normal(78, 6, 60),
    np.clip(rng.normal(68, 13, 60), 0, 100),
    np.append(rng.normal(81, 5, 57), [55, 58, 99]),
]
colors = ["#ffafcc", "#a2d2ff", "#b5e48c", "#ffd166"]

fig, ax = plt.subplots(figsize=(8, 5), layout="constrained")
boxes = ax.boxplot(scores, tick_labels=labels, patch_artist=True,
                   medianprops={"color": "black", "linewidth": 2})
for patch, color in zip(boxes["boxes"], colors):
    patch.set_facecolor(color)

ax.set_ylabel("Exam score")
ax.set_title("Scores by class (sample data)")
plt.show()

Four colored box plots of exam scores, with Class D highest and Class C the most spread out

tick_labels was called labels before Matplotlib 3.9. The old name raised a deprecation warning in 3.9 and 3.10 and was removed in 3.11, where it fails with TypeError: Axes.boxplot() got an unexpected keyword argument 'labels'. On 3.8 or older, use labels=labels.

A simple Matplotlib box plot

The shortest version takes only the data:

plt.figure(figsize=(8, 5), layout="constrained")
plt.boxplot(scores)
plt.show()

Default Matplotlib box plot with four unfilled boxes numbered 1 to 4

A single array draws one box. A 2D array draws one box per column.

What do the parts of a box plot mean?

fig, ax = plt.subplots(figsize=(8, 4), layout="constrained")
parts = ax.boxplot(scores[3], orientation="horizontal", widths=0.4)

q1, median, q3 = np.percentile(scores[3], [25, 50, 75])
low, high = (line.get_xdata()[1] for line in parts["whiskers"])
outliers = parts["fliers"][0].get_xdata()

for x, y, text in [
    (low, 1.3, "lower\nwhisker"), (q1, 0.62, "Q1"), (median, 1.3, "median"),
    (q3, 0.62, "Q3"), (high, 1.3, "upper\nwhisker"), (outliers.min(), 0.8, "outliers"),
]:
    ax.text(x, y, text, ha="center", va="center")
ax.set_ylim(0.5, 1.5)
ax.set_yticks([])
ax.set_xlabel("Exam score (Class D)")
plt.show()

Horizontal box plot labeled with the lower whisker, Q1, median, Q3, upper whisker, and outliers

  • The box runs from the first quartile (Q1) to the third (Q3), so it holds the middle half of the data.
  • The line inside is the median.
  • Each whisker ends at the most extreme data point within 1.5 × IQR of the box, where IQR = Q3 − Q1.
  • Points beyond the whiskers are drawn as outliers ("fliers").

orientation needs Matplotlib 3.10 or newer.

Box plots in Matplotlib with custom colors and styles

patch_artist=True makes the boxes fillable. The *props dictionaries style each part, and boxplot() returns those parts if you want to change them one at a time, as the Quick Example does with boxes["boxes"].

fig, ax = plt.subplots(figsize=(8, 5), layout="constrained")
ax.boxplot(
    scores, tick_labels=labels, patch_artist=True, widths=0.5,
    boxprops={"facecolor": "#264653", "edgecolor": "#264653"},
    medianprops={"color": "#e9c46a", "linewidth": 3},
    whiskerprops={"color": "#264653", "linewidth": 1.5},
    capprops={"color": "#264653", "linewidth": 1.5},
    flierprops={"marker": "D", "markerfacecolor": "#e76f51",
                "markeredgecolor": "none"},
)
ax.set_ylabel("Exam score")
plt.show()

Dark teal box plots with yellow median lines and orange diamond outliers

Horizontal box plot

Pass orientation="horizontal". Horizontal boxes leave room for long group names.

fig, ax = plt.subplots(figsize=(8, 4.5), layout="constrained")
ax.boxplot(scores, tick_labels=labels, orientation="horizontal")
ax.invert_yaxis()  # Class A at the top
ax.set_xlabel("Exam score")
plt.show()

Horizontal box plots of exam scores with Class A at the top

Older code uses vert=False, which is deprecated as of Matplotlib 3.11.

Show the mean and a notch

showmeans=True adds a marker at each mean. notch=True pinches the box around the median to show an approximate 95% confidence interval; if two notches don't overlap, that suggests the medians differ.

fig, ax = plt.subplots(figsize=(8, 5), layout="constrained")
ax.boxplot(
    scores, tick_labels=labels, notch=True, showmeans=True,
    meanprops={"marker": "o", "markerfacecolor": "white",
               "markeredgecolor": "black"},
)
ax.set_ylabel("Exam score")
plt.show()

Notched box plots with a white dot marking the mean of each class

Change the whiskers or hide outliers

whis sets the whisker rule: a number is a multiple of the IQR (default 1.5), and a pair such as (5, 95) places the whiskers at those percentiles. showfliers=False hides the outlier points.

fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(11, 4), sharey=True,
                                    layout="constrained")
ax1.boxplot(scores)
ax1.set_title("Default (whis=1.5)")
ax2.boxplot(scores, whis=(0, 100))
ax2.set_title("whis=(0, 100): min to max")
ax3.boxplot(scores, showfliers=False)
ax3.set_title("showfliers=False")
plt.show()

Three versions of the box plots: default whiskers with outliers, whiskers covering the full range, and outliers hidden

Hiding outliers changes only the drawing, so say so in the chart's caption.

Add the data points to a box plot

Draw the points with ax.scatter() at each box's position (1, 2, 3, ...), with a little random horizontal jitter:

fig, ax = plt.subplots(figsize=(8, 5), layout="constrained")
ax.boxplot(scores, tick_labels=labels, showfliers=False)  # points show them

for position, values in enumerate(scores, start=1):
    jitter = rng.uniform(-0.12, 0.12, len(values))
    ax.scatter(position + jitter, values, s=14, alpha=0.5, color="#7209b7")
ax.set_ylabel("Exam score")
plt.show()

Box plots with every student's score drawn as a jittered dot

A raincloud plot adds the density as well, which reveals multiple peaks that a box plot hides.

Grouped box plots

Use positions to place two sets of boxes side by side:

spring = scores
fall = [values - drop + rng.normal(0, 3, len(values))
        for values, drop in zip(scores, [6, 2, 9, 4])]
x = np.arange(len(labels))

fig, ax = plt.subplots(figsize=(8, 5), layout="constrained")
for data, offset, color, term in [(fall, -0.18, "#f4a261", "Fall"),
                                  (spring, 0.18, "#2a9d8f", "Spring")]:
    ax.boxplot(data, positions=x + offset, widths=0.3, patch_artist=True,
               boxprops={"facecolor": color}, medianprops={"color": "black"},
               manage_ticks=False, label=term)

ax.set_xticks(x, labels)
ax.set_ylabel("Exam score")
ax.legend(loc="lower right")
plt.show()

Grouped box plots comparing fall and spring scores for each class, with spring higher

The label argument for legends needs Matplotlib 3.9 or newer.

Box plot from a pandas DataFrame

boxplot() doesn't skip missing values: a column containing NaN draws an empty box. Drop them column by column:

import pandas as pd

df = pd.DataFrame({name: values for name, values in zip(labels, scores)})
df.iloc[:5, 0] = np.nan

fig, ax = plt.subplots(figsize=(8, 5), layout="constrained")
ax.boxplot([df[col].dropna() for col in df], tick_labels=df.columns)
plt.show()

df.plot.box() and df.boxplot() are shortcuts that handle missing values themselves.

Box plot, violin plot, or histogram?

Chart Best for
Box plot Comparing medians and spread across many groups
Violin plot Seeing the shape of each group's distribution
Histogram Looking closely at one or two distributions

For interactive versions, see box and violin plots in Plotly.

Similar Topics