svgpr-curve
Precision–recall curve
How much precision does the model keep as it finds more of the positives?
How to read it
- Read each point as a threshold: its recall (how many positives you catch) and precision (how many flagged are right).
- Higher and further right is better.
- Compare with the no-skill line, which sits at the share of positives.
- Callout 1: High precision at low recall: the most confident predictions.
- Callout 2: As recall rises, precision falls: you flag more wrong rows.
- 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
# Precision–recall curve — Codesplash Chart Lab (recipe "pr-curve")
# controls: baseline=0
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("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
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 = go.Figure()
for i, (name, d) in enumerate(series):
ap = average_precision(d[REC], d[PREC])
fig.add_scatter(x=d[REC], y=d[PREC], mode="lines", line=dict(color=PALETTE[i % len(PALETTE)], width=2, shape="hv"), name=f"{name + ' ' if name else ''}AP {ap:.3f}")
if 0 < BASELINE < 1:
fig.add_hline(y=BASELINE, line=dict(color=REF, dash="dash", width=1), annotation_text=f"no skill ({BASELINE:.0%})")
fig.update_layout(xaxis=dict(range=[0, 1], title=REC), yaxis=dict(range=[0, 1.02], title=PREC))
fig.show()Needs pandas, numpy, plotly · reads pr-curve-demo.csv · app theme from the optional codesplash helper
# Precision–recall curve — Codesplash Chart Lab (recipe "pr-curve")
# controls: baseline=0
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("pr-curve-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["model"]] <- factor(df[["model"]], levels = c("XGBoost", "Logistic regression"))
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
rec_col <- "recall"
prec_col <- "precision"
curve_col <- "model"
baseline <- 0 # prevalence: the no-skill precision (0 = none)
d <- data.frame(r = df[[rec_col]], p = df[[prec_col]], g = if (is.null(curve_col)) "" else as.character(df[[curve_col]]))
d <- d[!is.na(d$r) & !is.na(d$p), ]
d <- d[order(d$g, d$r), ]
lv <- if (is.null(curve_col)) "" else levels_of(df[[curve_col]])
ap <- vapply(lv, function(k) { s <- d[d$g == k, ]; sum(diff(c(0, s$r)) * s$p) }, numeric(1)) # step-wise average precision
d$g <- factor(d$g, levels = lv, labels = trimws(paste(lv, sprintf("AP %.3f", ap))))
p <- ggplot(d, aes(r, p, colour = g)) +
{ if (baseline > 0 && baseline < 1) geom_hline(yintercept = baseline, linetype = "dashed", colour = ref_col) } +
geom_step(linewidth = 0.9) + scale_colour_manual(values = cs_cat) +
coord_cartesian(xlim = c(0, 1), ylim = c(0, 1.02)) + labs(x = rec_col, y = prec_col, colour = NULL) + theme_cs
print(p)Needs ggplot2 · reads pr-curve-demo.csv · app theme from the optional codesplashr helper