svgroc-curve
ROC curve
How well does a score separate positives from negatives at every cutoff?
How to read it
- Read each point as a cutoff's false-positive rate and true-positive rate.
- Closer to the top-left corner is better; the diagonal is no better than chance.
- Read AUC in the legend, then mark the cutoff you would really use.
- Callout 1: The chosen cutoff: its sensitivity and specificity.
- Callout 2: Diagonal: a score with no ability to separate.
- Callout 3: AUC: the chance a positive outscores a negative.
Watch out
- AUC ignores prevalence and the costs of errors. With rare positives, check the precision–recall curve too.
Defaults
- Chance diagonal
- On
- Draw the line a score with no skill would follow.
Pinned in the code
- Draws the engine's numbers as given (precomputed by the Python or R analysis); the chart computes nothing statistical.
- Points are sorted by FPR then TPR and closed at (0, 0) and (1, 1); the legend AUC is the trapezoid area under the drawn points (equal to the engine's empirical AUC when every threshold is supplied). Inference (DeLong CI, tests) comes from the engine.
- The chosen cutoff (Youden, closest-to-(0,1) or cost-based, as the analysis says) is ringed and labelled with its sensitivity and specificity.
# ROC curve — Codesplash Chart Lab (recipe "roc-curve")
# controls: diagonal=true
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("roc-curve-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["marker"] = pd.Categorical(df["marker"].astype("string"), categories=["troponin", "CRP"])
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)))
def truthy(s):
return s.astype(str).str.strip().str.lower().isin(["true", "1", "yes", "t"])
def trapezoid(x, y):
x, y = np.asarray(x, float), np.asarray(y, float)
return float(np.sum(np.diff(x) * (y[1:] + y[:-1]) / 2))
FPR = "fpr"
TPR = "tpr"
CURVE = "marker"
OPT = "cutoff"
DIAGONAL = True
groups = levels_of(df[CURVE]) if CURVE else [None]
series = []
for name in groups:
d = df if name is None else df[df[CURVE].astype(str) == str(name)]
series.append((name if name is not None else "", d.dropna(subset=[FPR]).sort_values([FPR, TPR], kind="mergesort")))
fig, ax = plt.subplots(figsize=(6, 6))
if DIAGONAL:
ax.plot([0, 1], [0, 1], color="grey", linestyle="--", linewidth=1)
for i, (name, d) in enumerate(series):
col = PALETTE[i % len(PALETTE)]
auc = trapezoid(d[FPR], d[TPR])
ax.plot(d[FPR], d[TPR], color=col, linewidth=2, label=f"{name + ' ' if name else ''}AUC {auc:.3f}")
if OPT:
o = d[truthy(d[OPT])]
ax.scatter(o[FPR], o[TPR], s=60, facecolors="white", edgecolors=col, linewidths=2, zorder=3)
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.set_xlabel(FPR + " (1 − specificity)")
ax.set_ylabel(TPR + " (sensitivity)")
ax.legend(fontsize=8, loc="lower right")
plt.show()Needs pandas, numpy, matplotlib · reads roc-curve-demo.csv · app theme from the optional codesplash helper
# ROC curve — Codesplash Chart Lab (recipe "roc-curve")
# controls: diagonal=true
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("roc-curve-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["marker"] = pd.Categorical(df["marker"].astype("string"), categories=["troponin", "CRP"])
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)))
def truthy(s):
return s.astype(str).str.strip().str.lower().isin(["true", "1", "yes", "t"])
def trapezoid(x, y):
x, y = np.asarray(x, float), np.asarray(y, float)
return float(np.sum(np.diff(x) * (y[1:] + y[:-1]) / 2))
FPR = "fpr"
TPR = "tpr"
CURVE = "marker"
OPT = "cutoff"
DIAGONAL = True
groups = levels_of(df[CURVE]) if CURVE else [None]
series = []
for name in groups:
d = df if name is None else df[df[CURVE].astype(str) == str(name)]
series.append((name if name is not None else "", d.dropna(subset=[FPR]).sort_values([FPR, TPR], kind="mergesort")))
fig = go.Figure()
if DIAGONAL:
fig.add_scatter(x=[0, 1], y=[0, 1], mode="lines", line=dict(color="grey", dash="dash", width=1), name="chance", showlegend=False)
for i, (name, d) in enumerate(series):
col = PALETTE[i % len(PALETTE)]
auc = trapezoid(d[FPR], d[TPR])
fig.add_scatter(x=d[FPR], y=d[TPR], mode="lines", line=dict(color=col, width=2), name=f"{name + ' ' if name else ''}AUC {auc:.3f}")
if OPT:
o = d[truthy(d[OPT])]
fig.add_scatter(x=o[FPR], y=o[TPR], mode="markers", marker=dict(size=11, color="white", line=dict(color=col, width=2)), showlegend=False)
fig.update_layout(xaxis=dict(range=[0, 1], title=FPR + " (1 − specificity)"), yaxis=dict(range=[0, 1], title=TPR + " (sensitivity)", scaleanchor="x"))
fig.show()Needs pandas, numpy, plotly · reads roc-curve-demo.csv · app theme from the optional codesplash helper
# ROC curve — Codesplash Chart Lab (recipe "roc-curve")
# controls: diagonal=true
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("roc-curve-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["cutoff"]] <- as.logical(df[["cutoff"]])
df[["marker"]] <- factor(df[["marker"]], levels = c("troponin", "CRP"))
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
truthy <- function(v) tolower(trimws(as.character(v))) %in% c("true", "1", "yes", "t")
fpr_col <- "fpr"
tpr_col <- "tpr"
curve_col <- "marker"
opt_col <- "cutoff"
show_diag <- TRUE
d <- data.frame(fpr = df[[fpr_col]], tpr = df[[tpr_col]], g = if (is.null(curve_col)) "" else as.character(df[[curve_col]]),
opt = if (is.null(opt_col)) FALSE else truthy(df[[opt_col]]))
d <- d[!is.na(d$fpr) & !is.na(d$tpr), ]
d <- d[order(d$g, d$fpr, d$tpr), ]
lv <- if (is.null(curve_col)) "" else levels_of(df[[curve_col]])
auc <- vapply(lv, function(k) { s <- d[d$g == k, ]; sum(diff(s$fpr) * (head(s$tpr, -1) + tail(s$tpr, -1)) / 2) }, numeric(1)) # trapezoid rule
labs_auc <- trimws(paste(lv, sprintf("AUC %.3f", auc)))
d$g <- factor(d$g, levels = lv, labels = labs_auc)
p <- ggplot(d, aes(fpr, tpr, colour = g)) +
{ if (show_diag) geom_abline(slope = 1, intercept = 0, linetype = "dashed", colour = "grey60") } +
geom_path(linewidth = 0.9) +
geom_point(data = d[d$opt, ], shape = 21, fill = "white", size = 3, stroke = 1.2) +
scale_colour_manual(values = cs_cat) + coord_equal(xlim = c(0, 1), ylim = c(0, 1)) +
labs(x = paste(fpr_col, "(1 − specificity)"), y = paste(tpr_col, "(sensitivity)"), colour = NULL) + theme_cs
print(p)Needs ggplot2 · reads roc-curve-demo.csv · app theme from the optional codesplashr helper