Skip to content
svgpr-curve

Precision–recall curve

How much precision does the model keep as it finds more of the positives?

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

How to read it

  1. Read each point as a threshold: its recall (how many positives you catch) and precision (how many flagged are right).
  2. Higher and further right is better.
  3. Compare with the no-skill line, which sits at the share of positives.
  1. Callout 1: High precision at low recall: the most confident predictions.
  2. Callout 2: As recall rises, precision falls: you flag more wrong rows.
  3. Callout 3: Average precision in the legend.

Watch out

  • Baselines change with prevalence: compare only models scored on the same positive share.

Defaults

No-skill baseline (prevalence; 0 = none)
0
Draw the precision of a model with no skill: the share of positives.
Range 0 to 1, step 0.01

Pinned in the code

  • Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
  • Points are joined in order of recall; the legend's AP is the step sum Σ (Rₙ − Rₙ₋₁)·Pₙ (scikit-learn's average precision), not the trapezoid area.
  • The no-skill baseline is the prevalence: a classifier that ranks at random has that precision at every recall.
  • Prefer this to ROC when positives are rare — ROC can look good while precision is poor.
# Precision–recall curve — Codesplash Chart Lab (recipe "pr-curve")
# controls: baseline=0
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("pr-curve-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["model"] = pd.Categorical(df["model"].astype("string"), categories=["XGBoost", "Logistic regression"])

_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")
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 average_precision(recall, precision):
    """Step-wise AP: Σ (R_k − R_{k−1}) · P_k over increasing recall (scikit-learn's definition)."""
    r, p = np.asarray(recall, float), np.asarray(precision, float)
    return float(np.sum(np.diff(np.concatenate([[0.0], r])) * p))
REC = "recall"
PREC = "precision"
CURVE = "model"
BASELINE = 0  # prevalence: the no-skill precision (0 = none)
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=[REC]).sort_values([REC], kind="mergesort")))
fig, ax = plt.subplots(figsize=(6.5, 5))
if 0 < BASELINE < 1:
    ax.axhline(BASELINE, color=REF, linestyle="--", linewidth=1, label=f"no skill ({BASELINE:.0%})")
for i, (name, d) in enumerate(series):
    ap = average_precision(d[REC], d[PREC])
    ax.step(d[REC], d[PREC], where="post", color=PALETTE[i % len(PALETTE)], linewidth=2, label=f"{name + ' ' if name else ''}AP {ap:.3f}")
ax.set_xlim(0, 1)
ax.set_ylim(0, 1.02)
ax.set_xlabel(REC)
ax.set_ylabel(PREC)
ax.legend(fontsize=8, loc="lower left")
plt.show()

Needs pandas, numpy, matplotlib · reads pr-curve-demo.csv · app theme from the optional codesplash helper