Error Bars
Measurements are never exact. A mean computed from a sample has uncertainty, and an honest chart shows it. Error bars are small lines that extend from each point (or bar) to show a range such as ± one standard deviation, a standard error or a confidence interval.
errorbar() basics
ax.errorbar(x, y, yerr=...) draws the points (joined by a line by default) plus vertical error bars:
import numpy as np
import matplotlib.pyplot as plt
dose = np.array([0, 5, 10, 20, 40])
response = np.array([2.1, 3.8, 5.2, 7.9, 9.6])
std = np.array([0.4, 0.6, 0.5, 0.9, 1.1])
fig, ax = plt.subplots()
ax.errorbar(dose, response, yerr=std, fmt="o-", capsize=4)
ax.set(xlabel="Dose (mg)", ylabel="Response", title="Mean ± 1 standard deviation")
plt.show()
for d, r, s in zip(dose, response, std):
print(f"dose {d:>2}: {r - s:.1f} .. {r + s:.1f}")dose 0: 1.7 .. 2.5
dose 5: 3.2 .. 4.4
dose 10: 4.7 .. 5.7
dose 20: 7.0 .. 8.8
dose 40: 8.5 .. 10.7
| Argument | Meaning |
|---|---|
yerr, xerr |
Error size: one number for all, one per point, or a 2×N array for asymmetric errors |
fmt |
Format string for the data points/line ("o", "s--", "none") |
capsize |
Length of the caps at the ends of the bars, in points |
elinewidth, ecolor |
Width and colour of the error lines |
capthick |
Thickness of the caps |
barsabove |
Draw the error bars above the markers |
Errors computed from data
Usually the error comes from repeated measurements. Here each condition was measured 8 times; we plot the mean with the standard error (std / sqrt(n)):
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(21)
temps = np.array([10, 20, 30, 40, 50])
# 8 repeated measurements per temperature (rows = repeats)
growth = 0.05 * temps + rng.normal(0, 0.35, (8, temps.size))
mean = growth.mean(axis=0)
sem = growth.std(axis=0, ddof=1) / np.sqrt(growth.shape[0])
fig, ax = plt.subplots()
ax.errorbar(temps, mean, yerr=sem, fmt="s", color="C2", ecolor="gray",
elinewidth=1.5, capsize=5, label="mean ± SEM")
ax.set(xlabel="Temperature (°C)", ylabel="Growth rate")
ax.legend()
plt.show()
print("means:", np.round(mean, 2).tolist())
print("SEM :", np.round(sem, 2).tolist())means: [0.63, 1.15, 1.31, 1.97, 2.67]
SEM : [0.07, 0.13, 0.16, 0.13, 0.09]
Tip: Always say in the label or caption what the bars mean. "±1 SD", "±SEM" and "95 % CI" have very different sizes, and a reader can't tell them apart from the picture.
Asymmetric and horizontal errors
For asymmetric errors pass a pair [lower, upper]. xerr adds horizontal bars, for example when the x value is uncertain too:
import numpy as np
import matplotlib.pyplot as plt
x = np.array([1.0, 2.0, 3.0, 4.0])
y = np.array([3.0, 4.5, 4.0, 6.0])
y_low = np.array([0.3, 0.5, 0.2, 0.6])
y_high = np.array([0.8, 1.2, 0.5, 1.5])
x_err = 0.15
fig, ax = plt.subplots()
ax.errorbar(x, y, yerr=[y_low, y_high], xerr=x_err, fmt="D", color="C3", capsize=3)
ax.set_title("Asymmetric y errors and fixed x errors")
ax.set_xlim(0.5, 4.5)
plt.show()
print("lower ends:", (y - y_low).tolist())
print("upper ends:", (y + y_high).tolist())lower ends: [2.7, 4.0, 3.8, 5.4]
upper ends: [3.8, 5.7, 4.5, 7.5]
Error bars on bar charts
bar() and barh() accept yerr/xerr directly:
import numpy as np
import matplotlib.pyplot as plt
methods = ["Lecture", "Video", "Practice", "Mixed"]
mean_score = np.array([64, 68, 77, 81])
ci95 = np.array([5.1, 4.2, 3.8, 4.5])
fig, ax = plt.subplots()
bars = ax.bar(methods, mean_score, yerr=ci95, capsize=6, color="C0", alpha=0.85)
ax.set(ylabel="Test score", ylim=(0, 100), title="Mean score with 95 % confidence interval")
plt.show()
best = methods[int(mean_score.argmax())]
print("Best method:", best, "| bars:", len(bars))Best method: Mixed | bars: 4
Shaded error bands
For a line with many points, individual bars become cluttered. A shaded band drawn with fill_between (see the next lesson) shows the same information more calmly:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 80)
mean = np.sin(x) + 0.1 * x
spread = 0.2 + 0.03 * x # uncertainty grows with x
fig, ax = plt.subplots()
ax.plot(x, mean, color="C0", label="forecast")
ax.fill_between(x, mean - spread, mean + spread, color="C0", alpha=0.25, label="±1 SD")
ax.legend(loc="upper left")
plt.show()
print(f"band width at start {2 * spread[0]:.2f}, at end {2 * spread[-1]:.2f}")band width at start 0.40, at end 1.00
Test yourself
Which argument adds caps to the ends of error bars?
- caps=True
- capsize
- capstyle
- endcap
How do you pass asymmetric vertical errors to errorbar?
- yerr=(low, high) as two scalars only
- yerr=[lower_array, upper_array]
- ylow= and yhigh=
- It is not supported
What does fmt="none" do in errorbar?
- Raises an error
- Draws only the error bars, without markers or line
- Uses the default style
- Hides the error bars