svgcd-diagram
Critical-difference diagram
Across folds, which models are reliably better than which?
How to read it
- Read the top axis as mean rank across folds: lower is better.
- A thick bar joins models the test could not separate.
- Compare distances with the critical difference at the top.
- Callout 1: The critical difference.
- Callout 2: A thick bar: these models can't be separated.
- Callout 3: A model and its mean rank.
Watch out
- Folds aren't fully independent, so the test can be optimistic. Use repeated folds if it matters.
Defaults
- Critical difference
- 1.93
- Nemenyi critical difference of mean ranks (the comparison sets it); 0 hides the bars.
- Range 0 to 20, 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.
- Ranks are per fold (1 = best model in that fold, ties averaged) and averaged across the folds every model shared.
- Bars join maximal runs of models within the critical difference (Demšar's layout); nested runs are drawn once.
- Folds share training rows, so the Friedman/Nemenyi tests are optimistic — read the diagram as an ordering, and use the paired corrected t for claims about one pair.
# Critical-difference diagram — Codesplash Chart Lab (recipe "cd-diagram")
# controls: cd=1.93
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("cd-diagram-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
L = "model"
R = "mean rank"
CD = 1.93 # critical difference
d = df[[L, R]].dropna().sort_values([R, L]).reset_index(drop=True)
ranks, names = d[R].to_numpy(float), d[L].astype(str).tolist()
cliques, last = [], -1 # Demšar: maximal runs of models within CD of each other
for i in range(len(ranks)):
j = i
while CD and j + 1 < len(ranks) and ranks[j + 1] - ranks[i] <= CD + 1e-12:
j += 1
if j > i and j > last:
cliques.append((i, j))
last = j
fig, ax = plt.subplots(figsize=(7, 3))
ax.plot(ranks, [0] * len(ranks), "o", color=PALETTE[0])
for k, (i, j) in enumerate(cliques):
ax.plot([ranks[i], ranks[j]], [-0.12 - 0.06 * k] * 2, color="black", linewidth=3)
for i, (r, n) in enumerate(zip(ranks, names)):
ax.annotate(f"{n} ({r:.2f})", (r, 0), xytext=(r, 0.15 + 0.1 * i), fontsize=8, ha="center", arrowprops=dict(arrowstyle="-", color="grey"))
ax.set_xlim(max(0.5, ranks.min() - 0.5), ranks.max() + 0.5)
ax.set_ylim(-0.3 - 0.06 * len(cliques), 0.3 + 0.1 * len(ranks))
ax.set_yticks([])
ax.set_xlabel("Mean rank across folds (1 = best)")
plt.show()Needs pandas, numpy, matplotlib · reads cd-diagram-demo.csv · app theme from the optional codesplash helper
# Critical-difference diagram — Codesplash Chart Lab (recipe "cd-diagram")
# controls: cd=1.93
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("cd-diagram-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
L = "model"
R = "mean rank"
CD = 1.93 # critical difference
d = df[[L, R]].dropna().sort_values([R, L]).reset_index(drop=True)
ranks, names = d[R].to_numpy(float), d[L].astype(str).tolist()
cliques, last = [], -1 # Demšar: maximal runs of models within CD of each other
for i in range(len(ranks)):
j = i
while CD and j + 1 < len(ranks) and ranks[j + 1] - ranks[i] <= CD + 1e-12:
j += 1
if j > i and j > last:
cliques.append((i, j))
last = j
fig = go.Figure()
fig.add_scatter(x=ranks, y=[0] * len(ranks), mode="markers+text", text=names, textposition="top center", marker=dict(color=PALETTE[0], size=10), showlegend=False)
for k, (i, j) in enumerate(cliques):
fig.add_scatter(x=[ranks[i], ranks[j]], y=[-0.12 - 0.06 * k] * 2, mode="lines", line=dict(color="black", width=4), showlegend=False)
fig.update_layout(xaxis_title="Mean rank across folds (1 = best)", yaxis=dict(visible=False, range=[-0.5, 0.5]))
fig.show()Needs pandas, numpy, plotly · reads cd-diagram-demo.csv · app theme from the optional codesplash helper
# Critical-difference diagram — Codesplash Chart Lab (recipe "cd-diagram")
# controls: cd=1.93
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("cd-diagram-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["model"]] <- factor(df[["model"]])
L <- "model"
R <- "mean rank"
CD <- 1.93 # critical difference
d <- data.frame(label = as.character(df[[L]]), rank = df[[R]])
d <- d[is.finite(d$rank), ]
d <- d[order(d$rank, d$label), ]
cl <- list(); last <- 0 # Demšar: maximal runs of models within CD of each other
if (!is.null(CD)) for (i in seq_len(nrow(d))) {
j <- i
while (j < nrow(d) && d$rank[j + 1] - d$rank[i] <= CD + 1e-12) j <- j + 1
if (j > i && j > last) { cl[[length(cl) + 1]] <- data.frame(x = d$rank[i], xend = d$rank[j], y = -0.12 - 0.06 * length(cl)); last <- j }
}
bars <- if (length(cl)) do.call(rbind, cl) else data.frame(x = numeric(), xend = numeric(), y = numeric())
d$h <- 0.15 + 0.1 * (seq_len(nrow(d)) - 1)
p <- ggplot(d) +
geom_segment(aes(rank, 0, xend = rank, yend = h), colour = "grey60") +
geom_point(aes(rank, 0), colour = cs_cat[[1]], size = 2.4) +
geom_text(aes(rank, h, label = sprintf("%s (%.2f)", label, rank)), size = 2.8, vjust = -0.4) +
geom_segment(aes(x, y, xend = xend, yend = y), bars, linewidth = 1.4) +
scale_x_continuous(expand = expansion(mult = 0.2)) +
labs(x = "Mean rank across folds (1 = best)", y = NULL) + theme_cs + theme(axis.text.y = element_blank(), panel.grid.major.y = element_blank(), panel.grid.minor.y = element_blank())
print(p)Needs ggplot2 · reads cd-diagram-demo.csv · app theme from the optional codesplashr helper