Skip to content
svgroc-curve

ROC curve

How well does a score separate positives from negatives at every cutoff?

Demo data · seed 20261101 · 322 rows · default settings · 640 × 360SVG, lightSVG, darkDemo CSV

How to read it

  1. Read each point as a cutoff's false-positive rate and true-positive rate.
  2. Closer to the top-left corner is better; the diagonal is no better than chance.
  3. Read AUC in the legend, then mark the cutoff you would really use.
  1. Callout 1: The chosen cutoff: its sensitivity and specificity.
  2. Callout 2: Diagonal: a score with no ability to separate.
  3. 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