svginterval-coverage
Interval coverage
Do prediction intervals contain the truth as often as they promise?
How to read it
- Read x as the promised coverage, y as what was achieved.
- On the diagonal: honest intervals.
- Below the diagonal: intervals are too narrow.
- Callout 1: On the diagonal: honest intervals.
- Callout 2: Below the diagonal: overconfident.
- Callout 3: The perfect-calibration line.
Watch out
- Overall coverage can hide subgroups that are badly covered.
Defaults
No settings: the chart draws one way.
Pinned in the code
- Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
- Points below the diagonal under-cover (intervals too narrow); split-conformal intervals guarantee at least nominal coverage on exchangeable data. Compare widths only between methods with adequate coverage.
# Interval coverage — Codesplash Chart Lab (recipe "interval-coverage")
# 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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_DASHES = ["-", (0, (6, 3)), (0, (1.5, 2.5)), (0, (8, 3, 2, 3)), (0, (12, 4)), (0, (3, 3)), (0, (8, 2, 2, 2, 2, 2)), (0, (1.5, 5))]
SERIES_MARKERS = ["o", "s", "^", "D", "P", "*", "2", "v"]
df = pd.read_csv("interval-coverage-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["method"] = pd.Categorical(df["method"].astype("string"), categories=["Split conformal", "CQR", "Gaussian (model SD)"])
def levels_of(s):
"""Declared level order (categoricals), else order of first appearance."""
if isinstance(s.dtype, pd.CategoricalDtype):
return [v for v in s.cat.categories if (s == v).any()]
return list(dict.fromkeys(s.dropna().astype(str)))
N = "nominal coverage"
C = "empirical coverage"
W = "mean width ($100k)"
M = "method"
groups = levels_of(df[M]) if M else [None]
series = []
for name in groups:
d = df if name is None else df[df[M].astype(str) == str(name)]
series.append((name if name is not None else "", d.dropna(subset=[N]).sort_values(N)))
fig, ax = plt.subplots(figsize=(6, 5))
lo = max(0, min(df[N].min(), df[C].min()) - 0.05)
ax.plot([lo, 1], [lo, 1], color="grey", linestyle="--", linewidth=1, label="perfect calibration")
for i, (name, d) in enumerate(series):
ax.plot(d[N], d[C], marker=SERIES_MARKERS[i % 8], linestyle=SERIES_DASHES[i % 8], ms=5, color=PALETTE[i % len(PALETTE)], linewidth=1.8, label=name or C) # dash + marker per method, as in the app
ax.set_xlim(lo, 1)
ax.set_ylim(lo, 1)
ax.set_xlabel(N)
ax.set_ylabel(C)
ax.legend(fontsize=8)
plt.show()Needs pandas, numpy, matplotlib · reads interval-coverage-demo.csv · app theme from the optional codesplash helper
# Interval coverage — Codesplash Chart Lab (recipe "interval-coverage")
# 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
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_DASHES = ["solid", "6px,3px", "1.5px,2.5px", "8px,3px,2px,3px", "12px,4px", "3px,3px", "8px,2px,2px,2px,2px,2px", "1.5px,5px"]
SERIES_MARKERS = ["circle", "square", "triangle-up", "diamond", "cross", "star", "y-up", "triangle-down"]
df = pd.read_csv("interval-coverage-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["method"] = pd.Categorical(df["method"].astype("string"), categories=["Split conformal", "CQR", "Gaussian (model SD)"])
def levels_of(s):
"""Declared level order (categoricals), else order of first appearance."""
if isinstance(s.dtype, pd.CategoricalDtype):
return [v for v in s.cat.categories if (s == v).any()]
return list(dict.fromkeys(s.dropna().astype(str)))
N = "nominal coverage"
C = "empirical coverage"
W = "mean width ($100k)"
M = "method"
d = df.dropna(subset=[N, C]).sort_values(N)
fig = px.line(d, x=N, y=C, color=M, markers=True, hover_data=[W] if W else None, color_discrete_sequence=PALETTE,
line_dash=M, line_dash_sequence=SERIES_DASHES, symbol=M, symbol_sequence=SERIES_MARKERS) # dash + marker per method, as in the app
lo = max(0, min(d[N].min(), d[C].min()) - 0.05)
fig.add_shape(type="line", x0=lo, y0=lo, x1=1, y1=1, line=dict(color="grey", dash="dash"))
fig.update_layout(legend_title=None)
fig.show()Needs pandas, numpy, plotly · reads interval-coverage-demo.csv · app theme from the optional codesplash helper
# Interval coverage — Codesplash Chart Lab (recipe "interval-coverage")
# 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))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_linetypes <- c("solid", "63", "23", "8323", "C4", "33", "822222", "25")
cs_shapes <- c(16, 15, 17, 18, 3, 8, 4, 25)
df <- read.csv("interval-coverage-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["method"]] <- factor(df[["method"]], levels = c("Split conformal", "CQR", "Gaussian (model SD)"))
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
n_col <- "nominal coverage"
c_col <- "empirical coverage"
w_col <- "mean width ($100k)"
m_col <- "method"
d <- data.frame(n = df[[n_col]], cov = df[[c_col]], m = if (is.null(m_col)) "" else factor(as.character(df[[m_col]]), levels = levels_of(df[[m_col]])))
d$w <- if (is.null(w_col)) NA_real_ else df[[w_col]]
lo <- max(0, min(c(d$n, d$cov), na.rm = TRUE) - 0.05)
p <- ggplot(d, aes(n, cov, colour = m)) + geom_abline(slope = 1, intercept = 0, colour = "grey50", linetype = "dashed") +
geom_line(aes(linetype = m)) + geom_point(aes(shape = m), size = 2) + coord_equal(xlim = c(lo, 1), ylim = c(lo, 1)) + # dash + marker per method, as in the app
scale_colour_manual(values = cs_cat) + scale_linetype_manual(values = cs_linetypes) + scale_shape_manual(values = cs_shapes) +
labs(x = n_col, y = c_col, colour = NULL, linetype = NULL, shape = NULL) + theme_cs
print(p)Needs ggplot2 · reads interval-coverage-demo.csv · app theme from the optional codesplashr helper