TExcelTAD
Home › Matplotlib › Box & Violin Plots

Box & Violin Plots

A histogram describes one distribution in detail. To compare several distributions side by side, box plots and violin plots are more compact: each group gets one narrow shape that summarises its centre, spread and outliers.

Reading a box plot

Part Shows
Line inside the box the median (50th percentile)
Box edges the quartiles Q1 (25 %) and Q3 (75 %); the box height is the IQR
Whiskers the furthest data points within 1.5 × IQR of the box
Circles (fliers) outliers beyond the whiskers

A first box plot

ax.boxplot() takes a list of datasets, one box per dataset:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(10)
route_a = rng.normal(32, 4, 120)
route_b = rng.normal(29, 7, 120)
route_c = np.concatenate([rng.normal(27, 3, 115), [45, 48, 50, 52, 55]])  # a few bad days

fig, ax = plt.subplots()
ax.boxplot([route_a, route_b, route_c], labels=["Route A", "Route B", "Route C"])
ax.set(ylabel="Commute time (min)", title="Which route is most reliable?")
plt.show()

for name, data in zip("ABC", [route_a, route_b, route_c]):
    q1, med, q3 = np.percentile(data, [25, 50, 75])
    print(f"Route {name}: median {med:.1f}, IQR {q3 - q1:.1f}")
Route A: median 31.3, IQR 5.0
Route B: median 27.5, IQR 8.9
Route C: median 26.7, IQR 4.0

Route C has the lowest median but five outliers; route B is the most spread out.

Note: Matplotlib 3.9 renamed the labels= argument of boxplot to tick_labels=. This course uses Matplotlib 3.8, where it is still labels=; in newer versions the old name is deprecated.

Styling boxes

boxplot() has many options. The most useful:

Argument Effect
vert=False horizontal boxes
patch_artist=True boxes become filled patches you can colour
notch=True notches show a confidence interval for the median
showmeans=True also mark the mean
widths box width
whis whisker reach (default 1.5 × IQR; (0, 100) = min to max)
showfliers=False hide outliers
python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(3)
groups = {"Control": rng.normal(50, 10, 80),
          "Diet": rng.normal(56, 9, 80),
          "Exercise": rng.normal(60, 12, 80),
          "Both": rng.normal(66, 8, 80)}
colors = ["#adb5bd", "#74c0fc", "#8ce99a", "#ffd43b"]

fig, ax = plt.subplots()
result = ax.boxplot(list(groups.values()), vert=False, patch_artist=True,
                    showmeans=True, widths=0.6)
for box, color in zip(result["boxes"], colors):
    box.set_facecolor(color)
ax.set_yticks(range(1, 5), groups.keys())
ax.set(xlabel="Fitness score")
plt.show()

print("Artist groups returned:", sorted(result.keys()))
Artist groups returned: ['boxes', 'caps', 'fliers', 'means', 'medians', 'whiskers']

boxplot() returns a dictionary of the drawn pieces (boxes, medians, whiskers, caps, fliers, means) so you can style each one.

Violin plots

A box plot hides the shape of the distribution: a group with two peaks gets the same box as a group with one. A violin plot draws a smoothed density (a kernel density estimate) mirrored around the centre, so the shape becomes visible:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(14)
one_peak = rng.normal(0, 1, 400)
two_peaks = np.concatenate([rng.normal(-1.5, 0.5, 200), rng.normal(1.5, 0.5, 200)])
skewed = rng.exponential(1, 400) - 1

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9, 4), sharey=True)
data = [one_peak, two_peaks, skewed]
names = ["one peak", "two peaks", "skewed"]

ax1.boxplot(data, labels=names)
ax1.set_title("Box plots")
ax2.violinplot(data, showmedians=True)
ax2.set_xticks([1, 2, 3], names)
ax2.set_title("Violin plots")
plt.show()

print("Medians:", [round(float(np.median(d)), 2) for d in data])
Medians: [0.04, -0.01, -0.28]

On the left, "one peak" and "two peaks" look almost the same. On the right the difference is obvious.

Styling violins

violinplot() returns a dictionary as well; the shapes are under "bodies":

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(5)
weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri"]
orders = [rng.gamma(shape=4 + i, scale=5, size=200) for i in range(5)]

fig, ax = plt.subplots(figsize=(7, 4))
parts = ax.violinplot(orders, showmeans=False, showmedians=True, widths=0.8)
for body in parts["bodies"]:
    body.set_facecolor("C4")
    body.set_edgecolor("black")
    body.set_alpha(0.6)
ax.set_xticks(range(1, 6), weekdays)
ax.set(ylabel="Order value (€)")
plt.show()

print("Medians:", [round(float(np.median(o)), 1) for o in orders])
Medians: [18.5, 24.9, 30.2, 32.1, 40.6]
Choose When
Box plot Comparing many groups; precise quartiles and outliers matter
Violin plot The shape (peaks, skew) matters; enough data for a smooth density
Histogram One or two groups in detail

Test yourself

What does the line inside a box plot's box show?

  1. The mean
  2. The median
  3. The mode
  4. The maximum

Which values are drawn as individual outlier points by default?

  1. The top and bottom 5 %
  2. Points beyond 1.5 × IQR from the box
  3. Points more than 3 standard deviations from the mean
  4. None

What can a violin plot reveal that a box plot cannot?

  1. The median
  2. The number of groups
  3. The shape of the distribution, e.g. two peaks
  4. Outliers