svgroc-compare
ROC comparison
Is one score really better than the other on these rows?
How to read it
- Compare the two curves: higher and further left is better.
- Read ΔAUC and its interval: how much better one score is on these rows.
- Read DeLong's p-value: it uses the pairing, so it's sharper than comparing two separate intervals.
- Callout 1: Score A runs above score B here.
- Callout 2: The difference, its interval and the test.
- Callout 3: Each score's AUC.
Watch out
- A small AUC gain can be useless at the threshold you would really use.
- Testing a nested model's added predictor this way is known to be conservative.
Defaults
- Interval level
- 0.95
- How often intervals built this way contain the true value, over repeated samples.
- Range 0.8 to 0.99, step 0.01
- Chance diagonal
- On
- Draw the line a score with no skill would follow.
Demo data
- Advantage of score A in the demo
- 0.6
- How much better separated score A is than score B in the demo data.
- Range 0 to 1.5, step 0.1
Pinned in the code
- AUC is the Mann–Whitney probability a positive outscores a negative, ties counting ½.
- DeLong, DeLong & Clarke-Pearson (1988): the paired variance of ΔAUC from the placement values, z = ΔAUC / SE, a normal two-sided p.
- Higher scores predict positives. Values match pROC::roc.test(method = "delong", paired = TRUE).
# ROC comparison — Codesplash Chart Lab (recipe "roc-compare")
# controls: level=0.95, diagonal=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats
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-compare-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
_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")
L = "event"
A = "new score"
B = "old score"
d = df.dropna(subset=[L, A, B])
pos = d[L].astype(str).str.lower().isin(["1", "true", "yes", "positive", "pos"]).to_numpy()
def components(s): # DeLong placement values
p, n = s[pos][:, None], s[~pos][None, :]
psi = (p > n) + 0.5 * (p == n)
return psi.mean(axis=1), psi.mean(axis=0)
def roc_points(s):
cuts = np.unique(s)[::-1]
return np.r_[0, [(s[~pos] >= t).mean() for t in cuts]], np.r_[0, [(s[pos] >= t).mean() for t in cuts]]
a, b = d[A].to_numpy(float), d[B].to_numpy(float)
(a10, a01), (b10, b01) = components(a), components(b)
auc_a, auc_b = a10.mean(), b10.mean()
var = np.var(a10 - b10, ddof=1) / len(a10) + np.var(a01 - b01, ddof=1) / len(a01) # paired, DeLong et al. (1988)
diff, se = auc_a - auc_b, np.sqrt(var)
z = diff / se
p_value = 2 * stats.norm.sf(abs(z))
q = stats.norm.ppf(1 - (1 - 0.95) / 2)
note = f"ΔAUC {diff:.3f} [{diff - q * se:.3f}, {diff + q * se:.3f}], DeLong z = {z:.2f}, p = {p_value:.3f}"
fig, ax = plt.subplots(figsize=(5.5, 5.5))
ax.plot([0, 1], [0, 1], color=REF, linestyle="--", linewidth=1)
for i, (s, name, auc) in enumerate(((a, A, auc_a), (b, B, auc_b))):
fpr, tpr = roc_points(s)
ax.step(fpr, tpr, where="post", color=PALETTE[i], label=f"{name} (AUC {auc:.3f})")
ax.set_xlabel("1 − specificity (false-positive rate)")
ax.set_ylabel("sensitivity (true-positive rate)")
ax.set_title(note, fontsize=9)
ax.legend(fontsize=8, loc="lower right")
plt.show()Needs pandas, numpy, matplotlib, scipy · reads roc-compare-demo.csv · app theme from the optional codesplash helper
# ROC comparison — Codesplash Chart Lab (recipe "roc-compare")
# controls: level=0.95, diagonal=true
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from scipy import stats
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-compare-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
_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")
L = "event"
A = "new score"
B = "old score"
d = df.dropna(subset=[L, A, B])
pos = d[L].astype(str).str.lower().isin(["1", "true", "yes", "positive", "pos"]).to_numpy()
def components(s): # DeLong placement values
p, n = s[pos][:, None], s[~pos][None, :]
psi = (p > n) + 0.5 * (p == n)
return psi.mean(axis=1), psi.mean(axis=0)
def roc_points(s):
cuts = np.unique(s)[::-1]
return np.r_[0, [(s[~pos] >= t).mean() for t in cuts]], np.r_[0, [(s[pos] >= t).mean() for t in cuts]]
a, b = d[A].to_numpy(float), d[B].to_numpy(float)
(a10, a01), (b10, b01) = components(a), components(b)
auc_a, auc_b = a10.mean(), b10.mean()
var = np.var(a10 - b10, ddof=1) / len(a10) + np.var(a01 - b01, ddof=1) / len(a01) # paired, DeLong et al. (1988)
diff, se = auc_a - auc_b, np.sqrt(var)
z = diff / se
p_value = 2 * stats.norm.sf(abs(z))
q = stats.norm.ppf(1 - (1 - 0.95) / 2)
note = f"ΔAUC {diff:.3f} [{diff - q * se:.3f}, {diff + q * se:.3f}], DeLong z = {z:.2f}, p = {p_value:.3f}"
fig = go.Figure()
fig.add_scatter(x=[0, 1], y=[0, 1], mode="lines", line=dict(color=REF, dash="dash"), showlegend=False)
for i, (s, name, auc) in enumerate(((a, A, auc_a), (b, B, auc_b))):
fpr, tpr = roc_points(s)
fig.add_scatter(x=fpr, y=tpr, mode="lines", line=dict(color=PALETTE[i], shape="hv"), name=f"{name} (AUC {auc:.3f})")
fig.update_layout(title=note, xaxis_title="1 − specificity (false-positive rate)", yaxis_title="sensitivity (true-positive rate)")
fig.show()Needs pandas, numpy, plotly, scipy · reads roc-compare-demo.csv · app theme from the optional codesplash helper
# ROC comparison — Codesplash Chart Lab (recipe "roc-compare")
# controls: level=0.95, 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-compare-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["event"]] <- factor(df[["event"]])
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
L <- "event"
A <- "new score"
B <- "old score"
d <- df[complete.cases(df[, c(L, A, B)]), ]
pos <- tolower(as.character(d[[L]])) %in% c("1", "true", "yes", "positive", "pos")
components <- function(s) { # DeLong placement values
psi <- outer(s[pos], s[!pos], function(p, n) (p > n) + 0.5 * (p == n))
list(v10 = rowMeans(psi), v01 = colMeans(psi))
}
roc_points <- function(s, name) {
cuts <- rev(sort(unique(s)))
data.frame(fpr = c(0, sapply(cuts, function(t) mean(s[!pos] >= t))), tpr = c(0, sapply(cuts, function(t) mean(s[pos] >= t))), name = name)
}
ca <- components(d[[A]]); cb <- components(d[[B]])
auc_a <- mean(ca$v10); auc_b <- mean(cb$v10)
se <- sqrt(var(ca$v10 - cb$v10) / length(ca$v10) + var(ca$v01 - cb$v01) / length(ca$v01)) # paired, DeLong et al. (1988)
diff <- auc_a - auc_b; z <- diff / se; pv <- 2 * pnorm(-abs(z))
q <- qnorm(1 - (1 - 0.95) / 2)
curves <- rbind(roc_points(d[[A]], sprintf("%s (AUC %.3f)", A, auc_a)), roc_points(d[[B]], sprintf("%s (AUC %.3f)", B, auc_b)))
p <- ggplot(curves, aes(fpr, tpr, colour = name)) +
geom_abline(slope = 1, intercept = 0, colour = ref_col, linetype = "dashed") +
geom_step(linewidth = 0.7) +
scale_colour_manual(values = cs_cat[1:2], name = NULL) +
coord_equal() +
labs(x = "1 − specificity (false-positive rate)", y = "sensitivity (true-positive rate)", subtitle = sprintf("ΔAUC %.3f [%.3f, %.3f], DeLong z = %.2f, p = %.3f", diff, diff - q * se, diff + q * se, z, pv)) + theme_cs
print(p)Needs ggplot2 · reads roc-compare-demo.csv · app theme from the optional codesplashr helper