svgbland-altman
Bland–Altman plot
Do two measurement methods agree, is there a bias, and does it change with the level measured?
How to read it
- Read the middle line as the average difference (bias).
- Read the outer lines as the limits within which most differences fall.
- Look for a slope or a funnel: the disagreement may change with the level.
- Callout 1: Bias: the mean difference.
- Callout 2: Upper limit of agreement.
- Callout 3: Lower limit of agreement.
Watch out
- Small limits don't prove agreement: compare them with what is clinically or practically acceptable.
Defaults
No settings: the chart draws one way.
Pinned in the code
- Draws the engine's numbers as given (precomputed by the Python or R analysis); the chart computes nothing statistical.
- Engine-supplied controls: bias, lower, upper (lines), biasLow/biasHigh, lowerLow/lowerHigh, upperLow/upperHigh (confidence bands), slope/intercept (proportional-bias regression).
- Without engine lines the chart shows bias = mean difference and limits bias ± 1.96·SD (SD with n − 1), as in Bland & Altman (1986).
# Bland–Altman plot — Codesplash Chart Lab (recipe "bland-altman")
# controls: defaults
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else plt.rcParams["axes.prop_cycle"].by_key()["color"]
df = pd.read_csv("bland-altman-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"]) # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"]) # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
MEAN = "mean of methods (L/min)"
DIFF = "Wright − mini (L/min)"
d = df.dropna(subset=[MEAN, DIFF])
n, bias, sd = len(d), d[DIFF].mean(), d[DIFF].std(ddof=1)
loa = (bias - 1.96 * sd, bias + 1.96 * sd) # 95% limits of agreement
t = stats.t.ppf(0.975, n - 1)
se_bias, se_loa = sd / np.sqrt(n), sd * np.sqrt(3 / n) # Bland & Altman (1999) approximate SEs
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.axhspan(bias - t * se_bias, bias + t * se_bias, color=PALETTE[0], alpha=0.12, lw=0)
for lim in loa:
ax.axhspan(lim - t * se_loa, lim + t * se_loa, color=GREY, alpha=0.35, lw=0)
ax.axhline(lim, color=REF, linestyle="--", linewidth=1)
ax.axhline(bias, color=PALETTE[0], linewidth=1.5)
ax.axhline(0, color="grey", linewidth=0.6)
ax.scatter(d[MEAN], d[DIFF], s=22, color=PALETTE[0], alpha=0.8)
for v, txt in [(bias, f"bias {bias:.3g}"), (loa[0], f"−1.96 SD {loa[0]:.3g}"), (loa[1], f"+1.96 SD {loa[1]:.3g}")]:
ax.annotate(txt, (1, v), xycoords=("axes fraction", "data"), xytext=(-4, 3), textcoords="offset points", ha="right", fontsize=8)
ax.set_xlabel(MEAN)
ax.set_ylabel(DIFF)
plt.show()Needs pandas, numpy, matplotlib, scipy · reads bland-altman-demo.csv · app theme from the optional codesplash helper
# Bland–Altman plot — Codesplash Chart Lab (recipe "bland-altman")
# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from scipy import stats
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("bland-altman-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"]) # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"]) # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
MEAN = "mean of methods (L/min)"
DIFF = "Wright − mini (L/min)"
d = df.dropna(subset=[MEAN, DIFF])
n, bias, sd = len(d), d[DIFF].mean(), d[DIFF].std(ddof=1)
loa = (bias - 1.96 * sd, bias + 1.96 * sd)
t = stats.t.ppf(0.975, n - 1)
se_bias, se_loa = sd / np.sqrt(n), sd * np.sqrt(3 / n)
fig = go.Figure()
fig.add_hrect(y0=bias - t * se_bias, y1=bias + t * se_bias, fillcolor=PALETTE[0], opacity=0.12, line_width=0)
for lim, label in [(loa[0], "−1.96 SD"), (loa[1], "+1.96 SD")]:
fig.add_hrect(y0=lim - t * se_loa, y1=lim + t * se_loa, fillcolor=GREY, opacity=0.35, line_width=0)
fig.add_hline(y=lim, line=dict(color=REF, dash="dash", width=1), annotation_text=f"{label} {lim:.3g}", annotation_position="top right")
fig.add_hline(y=bias, line=dict(color=PALETTE[0], width=1.5), annotation_text=f"bias {bias:.3g}", annotation_position="top right")
fig.add_scatter(x=d[MEAN], y=d[DIFF], mode="markers", marker=dict(color=PALETTE[0], size=7, opacity=0.8), showlegend=False)
fig.update_layout(xaxis_title=MEAN, yaxis_title=DIFF)
fig.show()Needs pandas, numpy, plotly, scipy · reads bland-altman-demo.csv · app theme from the optional codesplash helper
# Bland–Altman plot — Codesplash Chart Lab (recipe "bland-altman")
# controls: defaults
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("bland-altman-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
mean_col <- "mean of methods (L/min)"
diff_col <- "Wright − mini (L/min)"
d <- data.frame(m = df[[mean_col]], diff = df[[diff_col]])
d <- d[!is.na(d$m) & !is.na(d$diff), ]
n <- nrow(d); bias <- mean(d$diff); s <- sd(d$diff)
loa <- bias + c(-1.96, 1.96) * s # 95% limits of agreement
tq <- qt(0.975, n - 1); se_bias <- s / sqrt(n); se_loa <- s * sqrt(3 / n) # Bland & Altman (1999)
lines_df <- data.frame(y = c(loa, bias), lab = sprintf(c("−1.96 SD %.3g", "+1.96 SD %.3g", "bias %.3g"), c(loa, bias)))
p <- ggplot(d, aes(m, diff)) +
annotate("rect", xmin = -Inf, xmax = Inf, ymin = bias - tq * se_bias, ymax = bias + tq * se_bias, fill = cs_cat[1], alpha = 0.12) +
annotate("rect", xmin = -Inf, xmax = Inf, ymin = loa - tq * se_loa, ymax = loa + tq * se_loa, fill = grey_col, alpha = 0.35) +
geom_hline(yintercept = 0, colour = "grey70", linewidth = 0.3) +
geom_hline(yintercept = loa, linetype = "dashed", colour = ref_col) +
geom_hline(yintercept = bias, colour = cs_cat[1], linewidth = 0.8) +
geom_point(colour = cs_cat[1], alpha = 0.8, size = 1.8) +
geom_text(data = lines_df, aes(x = Inf, y = y, label = lab), hjust = 1.05, vjust = -0.4, size = 3) +
labs(x = mean_col, y = diff_col) + theme_cs
print(p)Needs ggplot2 · reads bland-altman-demo.csv · app theme from the optional codesplashr helper