svgdecision-curve
Decision curve
Across the range of risk thresholds a clinician might use, does acting on the model do more good than treating everyone or no one?
How to read it
- Read x as the risk threshold you'd act on.
- Read y as net benefit: true positives minus false positives weighted by the threshold.
- A model is useful where it's above treat-all and treat-none.
- Callout 1: The model above the treat-all line.
- Callout 2: Treat none: zero benefit.
- Callout 3: Treat all: benefit falls as the threshold rises.
Watch out
- Only thresholds you'd really use matter, so ignore the rest of the curve.
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.
- Net benefit = TP/n − FP/n · pₜ/(1 − pₜ). Strategies named all/treat all and none/treat none are drawn dashed; the y axis is clipped at −5% of the maximum so the treat-all line does not dominate (as in dcurves).
# Decision curve — Codesplash Chart Lab (recipe "decision-curve")
# 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("decision-curve-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["strategy"] = pd.Categorical(df["strategy"].astype("string"), categories=["Full model", "Clinical score", "Treat all", "Treat none"])
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)))
T = "threshold probability"
NB = "net benefit"
S = "strategy"
groups = levels_of(df[S]) if S else [None]
series = []
for name in groups:
d = df if name is None else df[df[S].astype(str) == str(name)]
series.append((name if name is not None else "", d.dropna(subset=[T]).sort_values(T)))
top = df[NB].max()
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.axhline(0, color="grey", linewidth=0.8)
k = 0
for name, d in series:
low = str(name).lower()
if "all" in low or "none" in low:
ax.plot(d[T], d[NB], color="grey" if "all" in low else "black", linestyle="--", linewidth=1.2, label=name)
else:
ax.plot(d[T], d[NB], color=PALETTE[k % len(PALETTE)], linewidth=2, label=name)
k += 1
ax.set_ylim(-0.05 * top, top * 1.08) # clip the treat-all line, as dcurves does
ax.set_xlabel(T)
ax.set_ylabel(NB)
ax.legend(fontsize=8)
plt.show()Needs pandas, numpy, matplotlib · reads decision-curve-demo.csv · app theme from the optional codesplash helper
# Decision curve — Codesplash Chart Lab (recipe "decision-curve")
# 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("decision-curve-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["strategy"] = pd.Categorical(df["strategy"].astype("string"), categories=["Full model", "Clinical score", "Treat all", "Treat none"])
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)))
T = "threshold probability"
NB = "net benefit"
S = "strategy"
d = df.dropna(subset=[T, NB]).sort_values(T)
top = d[NB].max()
fig = px.line(d, x=T, y=NB, color=S, color_discrete_sequence=PALETTE, category_orders={S: levels_of(d[S])})
fig.update_yaxes(range=[-0.05 * top, top * 1.08])
fig.update_layout(legend_title=None)
fig.show()Needs pandas, numpy, plotly · reads decision-curve-demo.csv · app theme from the optional codesplash helper
# Decision curve — Codesplash Chart Lab (recipe "decision-curve")
# 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("decision-curve-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["strategy"]] <- factor(df[["strategy"]], levels = c("Full model", "Clinical score", "Treat all", "Treat none"))
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
t_col <- "threshold probability"
nb_col <- "net benefit"
s_col <- "strategy"
d <- data.frame(t = df[[t_col]], nb = df[[nb_col]], s = factor(as.character(df[[s_col]]), levels = levels_of(df[[s_col]])))
top <- max(d$nb, na.rm = TRUE)
d$ref <- grepl("all|none", tolower(d$s))
p <- ggplot(d, aes(t, nb, colour = s, linetype = ref)) + geom_hline(yintercept = 0, colour = "grey60") + geom_line(linewidth = 0.9) +
coord_cartesian(ylim = c(-0.05 * top, top * 1.08)) + scale_linetype_manual(values = c("solid", "dashed"), guide = "none") +
scale_colour_manual(values = c(cs_cat, "grey50", "black")) + labs(x = t_col, y = nb_col, colour = NULL) + theme_cs
print(p)Needs ggplot2 · reads decision-curve-demo.csv · app theme from the optional codesplashr helper