svgcalibration
Calibration plot
Do predicted probabilities match observed frequencies?
How to read it
- Read each point as a group's mean predicted risk against its observed rate.
- Points on the diagonal: predictions match reality.
- Above the diagonal: the model under-predicts there; below: over-predicts.
- Callout 1: A group of rows: its predicted and observed risk.
- Callout 2: Diagonal: perfect calibration.
- Callout 3: Below the diagonal: predictions are too high here.
Watch out
- Groups depend on the binning, and a good AUC says nothing about calibration.
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.
- Groups are the engine's (e.g. Hosmer–Lemeshow deciles of risk, g = 10); intervals are the engine's binomial CIs.
- Probability axes are fixed to [0, 1] when every value lies in it; marker area ∝ group size.
# Calibration plot — Codesplash Chart Lab (recipe "calibration")
# 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("calibration-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")
PRED = "mean predicted risk"
OBS = "observed readmission rate"
N = "patients"
LO = "lower (Wilson)"
HI = "upper (Wilson)"
d = df.dropna(subset=[PRED, OBS])
fig, ax = plt.subplots(figsize=(6, 6))
ax.plot([0, 1], [0, 1], color=REF, linestyle="--", linewidth=1, label="perfect calibration")
if LO and HI:
ax.errorbar(d[PRED], d[OBS], yerr=[d[OBS] - d[LO], d[HI] - d[OBS]], fmt="none", ecolor=PALETTE[0], capsize=2, linewidth=1)
size = 20 + 160 * d[N] / d[N].max() if N else 40 # marker area ∝ n per group
ax.plot(d[PRED], d[OBS], color=PALETTE[0], linewidth=1)
ax.scatter(d[PRED], d[OBS], s=size, color=PALETTE[0], zorder=3)
lim = max(1e-9, float(max(d[PRED].max(), (d[HI] if HI else d[OBS]).max())) * 1.05)
ax.set_xlim(0, min(1, lim))
ax.set_ylim(0, min(1, lim))
ax.set_xlabel(PRED)
ax.set_ylabel(OBS)
ax.legend(fontsize=8, loc="upper left")
plt.show()Needs pandas, numpy, matplotlib · reads calibration-demo.csv · app theme from the optional codesplash helper
# Calibration plot — Codesplash Chart Lab (recipe "calibration")
# 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("calibration-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")
PRED = "mean predicted risk"
OBS = "observed readmission rate"
N = "patients"
LO = "lower (Wilson)"
HI = "upper (Wilson)"
d = df.dropna(subset=[PRED, OBS])
err = dict(type="data", symmetric=False, array=d[HI] - d[OBS], arrayminus=d[OBS] - d[LO]) if LO and HI else None
size = (7 + 13 * d[N] / d[N].max()) if N else 9
fig = go.Figure()
fig.add_scatter(x=[0, 1], y=[0, 1], mode="lines", line=dict(color=REF, dash="dash", width=1), name="perfect calibration")
fig.add_scatter(x=d[PRED], y=d[OBS], mode="lines+markers", error_y=err, marker=dict(size=size, color=PALETTE[0]), line=dict(color=PALETTE[0], width=1), name=OBS)
lim = min(1.0, float(max(d[PRED].max(), (d[HI] if HI else d[OBS]).max())) * 1.05)
fig.update_layout(xaxis=dict(range=[0, lim], title=PRED), yaxis=dict(range=[0, lim], title=OBS, scaleanchor="x"))
fig.show()Needs pandas, numpy, plotly · reads calibration-demo.csv · app theme from the optional codesplash helper
# Calibration plot — Codesplash Chart Lab (recipe "calibration")
# 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("calibration-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
pred_col <- "mean predicted risk"
obs_col <- "observed readmission rate"
n_col <- "patients"
lo_col <- "lower (Wilson)"
hi_col <- "upper (Wilson)"
d <- df[!is.na(df[[pred_col]]) & !is.na(df[[obs_col]]), ]
d <- data.frame(pred = d[[pred_col]], obs = d[[obs_col]], n = if (is.null(n_col)) 1 else d[[n_col]],
lo = if (is.null(lo_col)) NA_real_ else d[[lo_col]], hi = if (is.null(hi_col)) NA_real_ else d[[hi_col]])
lim <- min(1, max(d$pred, d$hi, d$obs, na.rm = TRUE) * 1.05)
p <- ggplot(d, aes(pred, obs)) + geom_abline(slope = 1, intercept = 0, linetype = "dashed", colour = ref_col) +
{ if (!all(is.na(d$lo))) geom_errorbar(aes(ymin = lo, ymax = hi), width = 0.01, colour = cs_cat[1]) } +
geom_line(colour = cs_cat[1]) + geom_point(aes(size = n), colour = cs_cat[1]) +
scale_size_area(max_size = 6, guide = if (is.null(n_col)) "none" else "legend") +
coord_equal(xlim = c(0, lim), ylim = c(0, lim)) + labs(x = pred_col, y = obs_col, size = n_col) + theme_cs
print(p)Needs ggplot2 · reads calibration-demo.csv · app theme from the optional codesplashr helper