svgmethod-comparison
Method comparison
Do two measurement methods agree, or is there constant or proportional bias?
How to read it
- Read the points as paired measurements.
- Compare the solid fit line with the dashed identity line.
- An intercept away from zero suggests constant bias; a slope away from 1, proportional bias.
- Callout 1: Fit line: how one method tracks the other.
- Callout 2: Identity line: perfect agreement.
- Callout 3: The fitted equation.
Watch out
- A high correlation doesn't mean agreement: two methods can correlate perfectly and still differ.
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 inferential.
- Both axes share one scale so the identity line is the diagonal.
- The band joins the lines (upper slope, lower intercept) and (lower slope, upper intercept) — Passing–Bablok's slope and intercept limits move together, pivoting near the data's centre.
- Linearity (the CUSUM test) and the fit's p-values are on the result card.
# Method comparison — Codesplash Chart Lab (recipe "method-comparison")
# controls: defaults
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
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("method-comparison-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")
def first(col):
"""The first finite value of a column the engine repeats on every row (None if absent)."""
if col is None:
return None
v = pd.to_numeric(df[col], errors="coerce").dropna()
return float(v.iloc[0]) if len(v) else None
X = "laboratory"
Y = "meter"
B = "slope"
A = "intercept"
BL = "slope low"
BH = "slope high"
AL = "intercept low"
AH = "intercept high"
d = df.dropna(subset=[X, Y])
lim = np.array([min(d[X].min(), d[Y].min()), max(d[X].max(), d[Y].max())])
b, a, bl, bh, al, ah = (first(k) for k in (B, A, BL, BH, AL, AH))
fig, ax = plt.subplots(figsize=(6, 6))
ax.plot(lim, lim, color=REF, linestyle="--", label="identity")
if None not in (bl, bh, al, ah): # slope limits move with the opposite intercept limits
ax.fill_between(lim, al + bh * lim, ah + bl * lim, color=PALETTE[0], alpha=0.1, lw=0, label="slope CI limits")
ax.scatter(d[X], d[Y], s=14, color=GREY, edgecolors=REF, linewidths=0.3)
if b is not None and a is not None:
ax.plot(lim, a + b * lim, color=PALETTE[0], linewidth=2, label=f"y = {a:.3g} + {b:.3g}·x")
ax.set_xlim(*lim)
ax.set_ylim(*lim)
ax.set_aspect("equal")
ax.set_xlabel(X)
ax.set_ylabel(Y)
ax.legend(fontsize=8)
plt.show()Needs pandas, numpy, matplotlib · reads method-comparison-demo.csv · app theme from the optional codesplash helper
# Method comparison — Codesplash Chart Lab (recipe "method-comparison")
# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
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("method-comparison-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")
def first(col):
"""The first finite value of a column the engine repeats on every row (None if absent)."""
if col is None:
return None
v = pd.to_numeric(df[col], errors="coerce").dropna()
return float(v.iloc[0]) if len(v) else None
X = "laboratory"
Y = "meter"
B = "slope"
A = "intercept"
BL = "slope low"
BH = "slope high"
AL = "intercept low"
AH = "intercept high"
d = df.dropna(subset=[X, Y])
lim = np.array([min(d[X].min(), d[Y].min()), max(d[X].max(), d[Y].max())])
b, a, bl, bh, al, ah = (first(k) for k in (B, A, BL, BH, AL, AH))
fig = go.Figure()
if None not in (bl, bh, al, ah):
fig.add_scatter(x=np.r_[lim, lim[::-1]], y=np.r_[al + bh * lim, (ah + bl * lim)[::-1]], fill="toself", mode="none", fillcolor="rgba(8, 89, 172, 0.1)", name="slope CI limits")
fig.add_scatter(x=lim, y=lim, mode="lines", line=dict(color=REF, dash="dash"), name="identity")
fig.add_scatter(x=d[X], y=d[Y], mode="markers", marker=dict(color=GREY, size=6), name="pairs")
if b is not None and a is not None:
fig.add_scatter(x=lim, y=a + b * lim, mode="lines", line=dict(color=PALETTE[0], width=3), name=f"y = {a:.3g} + {b:.3g}·x")
fig.update_xaxes(range=list(lim), title=X)
fig.update_yaxes(range=list(lim), title=Y, scaleanchor="x")
fig.show()Needs pandas, numpy, plotly · reads method-comparison-demo.csv · app theme from the optional codesplash helper
# Method comparison — Codesplash Chart Lab (recipe "method-comparison")
# 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("method-comparison-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
first_num <- function(col) { if (is.null(col)) return(NA_real_); v <- suppressWarnings(as.numeric(df[[col]])); v <- v[is.finite(v)]; if (length(v)) v[1] else NA_real_ }
x_col <- "laboratory"
y_col <- "meter"
b_col <- "slope"
a_col <- "intercept"
bl_col <- "slope low"
bh_col <- "slope high"
al_col <- "intercept low"
ah_col <- "intercept high"
d <- df[!is.na(df[[x_col]]) & !is.na(df[[y_col]]), ]
d <- data.frame(x = d[[x_col]], y = d[[y_col]])
lim <- range(c(d$x, d$y))
b <- first_num(b_col); a <- first_num(a_col); bl <- first_num(bl_col); bh <- first_num(bh_col); al <- first_num(al_col); ah <- first_num(ah_col)
band <- data.frame(x = lim, lo = al + bh * lim, hi = ah + bl * lim) # slope limits with the opposite intercept limits
p <- ggplot(d, aes(x, y)) +
{ if (!anyNA(c(bl, bh, al, ah))) geom_ribbon(data = band, aes(x, ymin = lo, ymax = hi), inherit.aes = FALSE, fill = cs_cat[1], alpha = 0.1) } +
geom_abline(intercept = 0, slope = 1, linetype = "dashed", colour = ref_col) +
geom_point(colour = grey_col) +
{ if (!is.na(b)) geom_abline(intercept = a, slope = b, colour = cs_cat[1], linewidth = 1) } +
coord_equal(xlim = lim, ylim = lim) + labs(x = x_col, y = y_col) + theme_cs
print(p)Needs ggplot2 · reads method-comparison-demo.csv · app theme from the optional codesplashr helper