# How to Make a Bland-Altman Plot in Python

> Make a Bland-Altman plot in Python with Matplotlib or statsmodels mean_diff_plot: bias, 95% limits of agreement with confidence intervals, and a log transform for growing spread.

Source: https://www.pythoncharts.com/python/bland-altman-plot-python/ | Published: 2026-11-27 | Author: Alex Scott | Category: Python | Tags: matplotlib, statsmodels, bland-altman plot, method comparison, agreement

A Bland-Altman plot checks whether two measurement methods agree. Plot the
**difference** between each pair of readings against their **average**, then add
lines at the mean difference and at mean ± 1.96 standard deviations (the limits
of agreement). In Python, draw it with Matplotlib or call
`statsmodels.api.graphics.mean_diff_plot()`. This post uses Matplotlib 3.11 and
statsmodels 0.15.

## Quick Example

A wrist heart rate sensor compared with a chest strap on 120 people:

```python
import matplotlib.pyplot as plt
import numpy as np

rng = np.random.default_rng(211)
true_rate = rng.uniform(55, 165, 120)
chest = true_rate + rng.normal(0, 1.5, 120)
wrist = true_rate + 2.0 + rng.normal(0, 4.0, 120)

mean = (wrist + chest) / 2
diff = wrist - chest
bias = diff.mean()
sd = diff.std(ddof=1)
low, high = bias - 1.96 * sd, bias + 1.96 * sd

fig, ax = plt.subplots(figsize=(8.5, 4.8))
ax.scatter(mean, diff, s=22, color="#5e548e", alpha=0.75)
for value, label, style in [(bias, "Bias", "-"),
                            (high, "Upper limit", "--"),
                            (low, "Lower limit", "--")]:
    ax.axhline(value, color="#bc4749", ls=style, lw=1.5)
    ax.text(1.01, value, f"{label}\n{value:+.1f}", va="center",
            transform=ax.get_yaxis_transform(), fontsize=9)
ax.set_xlabel("Average of the two readings (bpm)")
ax.set_ylabel("Wrist minus chest (bpm)")
plt.show()

print(f"bias {bias:.2f}, limits of agreement {low:.1f} to {high:.1f}")
```

```text
bias 2.76, limits of agreement -5.0 to 10.5
```

![Bland-Altman plot of wrist minus chest heart rate against their average, with a solid bias line near plus two and dashed limits of agreement](https://www.pythoncharts.com/python/bland-altman-plot-python/images/bland-altman-quick-example.png)

## How do I read a Bland-Altman plot?

- **Bias** (middle line): how much higher one method reads on average. Here the wrist sensor reads about 2.8 bpm high. The simulation built in 2, and the rest is sampling noise.
- **Limits of agreement:** about 95% of differences should fall between them, if the differences are roughly normal.
- **Pattern:** the points should form a level band. A slope or a funnel means agreement depends on the size of the measurement.

Whether the limits are acceptable is not a statistical question. Decide how large
a difference matters *before* looking, then check that both limits are inside it.

## Why not just use correlation?

Correlation measures whether two things move together, not whether they give the
same number. A sensor that always reads 20 bpm high has the same correlation as
an accurate one.

```python
shifted = wrist + 20
print(f"r = {np.corrcoef(chest, wrist)[0, 1]:.3f}, "
      f"mean difference {np.mean(wrist - chest):.1f}")
print(f"r = {np.corrcoef(chest, shifted)[0, 1]:.3f}, "
      f"mean difference {np.mean(shifted - chest):.1f}")
```

```text
r = 0.992, mean difference 2.8
r = 0.992, mean difference 22.8
```

## Add confidence intervals

The bias and limits are estimates from a sample. With `n` pairs, the standard
error of the bias is `sd / sqrt(n)` and of each limit is approximately
`sd * sqrt(1/n + 1.96**2 / (2 * (n - 1)))`.

```python
from scipy import stats

n = len(diff)
t = stats.t.ppf(0.975, n - 1)
half_bias = t * sd / np.sqrt(n)
half_limit = t * sd * np.sqrt(1 / n + 1.96**2 / (2 * (n - 1)))

fig, ax = plt.subplots(figsize=(8.5, 4.8))
ax.scatter(mean, diff, s=22, color="#5e548e", alpha=0.75)
for value, half in [(bias, half_bias), (high, half_limit), (low, half_limit)]:
    ax.axhline(value, color="#bc4749", lw=1.3)
    ax.axhspan(value - half, value + half, color="#bc4749", alpha=0.15)
ax.set_xlabel("Average of the two readings (bpm)")
ax.set_ylabel("Wrist minus chest (bpm)")
plt.show()

print(f"bias  {bias - half_bias:.1f} to {bias + half_bias:.1f}")
print(f"upper {high - half_limit:.1f} to {high + half_limit:.1f}")
print(f"lower {low - half_limit:.1f} to {low + half_limit:.1f}")
```

```text
bias  2.1 to 3.5
upper 9.3 to 11.7
lower -6.2 to -3.8
```

![Bland-Altman plot with shaded 95 percent confidence bands around the bias and both limits of agreement](https://www.pythoncharts.com/python/bland-altman-plot-python/images/bland-altman-confidence.png)

## Use statsmodels mean_diff_plot

```python
import statsmodels.api as sm

fig, ax = plt.subplots(figsize=(8.5, 4.8))
sm.graphics.mean_diff_plot(wrist, chest, ax=ax,
                           scatter_kwds={"color": "#386641", "s": 22})
plt.show()
```

![The statsmodels mean difference plot with labeled mean and standard deviation limit lines](https://www.pythoncharts.com/python/bland-altman-plot-python/images/bland-altman-statsmodels.png)

It plots the first argument minus the second. Change the limit width with
`sd_limit`. Its standard deviation uses `ddof=0`, so the limits are very
slightly narrower than the ones above.

## What if the spread grows with the measurement?

Many instruments have error proportional to the value, which makes a funnel.
Analyze the differences of the **logs**, then convert back to ratios.

```python
actual = np.exp(rng.uniform(np.log(5), np.log(200), 150))
lab = actual * np.exp(rng.normal(0, 0.04, 150))
handheld = actual * 1.06 * np.exp(rng.normal(0, 0.09, 150))

fig, axes = plt.subplots(1, 2, figsize=(10, 4.2))
avg = (lab + handheld) / 2
for ax, d, title in [
        (axes[0], handheld - lab, "Raw difference: funnel shape"),
        (axes[1], np.log(handheld / lab), "Log ratio: level band")]:
    m, s = d.mean(), d.std(ddof=1)
    ax.scatter(avg, d, s=16, color="#bc6c25", alpha=0.75)
    for v, style in [(m, "-"), (m + 1.96 * s, "--"), (m - 1.96 * s, "--")]:
        ax.axhline(v, color="#283618", ls=style)
    ax.set_title(title)
    ax.set_xlabel("Average reading")
axes[0].set_ylabel("Handheld minus lab")
axes[1].set_ylabel("ln(handheld / lab)")
fig.tight_layout()
plt.show()

logs = np.log(handheld / lab)
ratios = np.exp([logs.mean(), logs.mean() - 1.96 * logs.std(ddof=1),
                 logs.mean() + 1.96 * logs.std(ddof=1)])
print("ratio: bias {:.2f}, limits {:.2f} to {:.2f}".format(*ratios))
```

```text
ratio: bias 1.07, limits 0.88 to 1.29
```

![Two panels: raw differences fanning out as readings grow, and log ratios forming an even band](https://www.pythoncharts.com/python/bland-altman-plot-python/images/bland-altman-log.png)

The handheld reads about 7% higher than the lab on average, and about 95% of its
readings should fall between 12% below and 29% above the lab value.

## Practical tips

- Put the average on the x-axis, not one method's reading, unless that method is a true reference with negligible error.
- Repeated measurements from the same person aren't independent. The formulas here assume one pair per subject.
- Check the differences for normality with a [Q-Q plot](https://www.pythoncharts.com/python/qq-plot-python/).
- Report the sample size, bias, limits and their intervals together.

## Similar Topics

- [Q-Q Plots in Python](https://www.pythoncharts.com/python/qq-plot-python/)
- [Residual Plot for Regression in Python](https://www.pythoncharts.com/machine-learning/residual-plot-regression-python/)
- [Error Bars in Matplotlib](https://www.pythoncharts.com/matplotlib/matplotlib-error-bars/)
