svgcritical-difference
Critical-difference diagram
How do the groups rank, and which rank differences are not significant?
How to read it
- Read the top axis as mean rank.
- A thick bar joins groups whose ranks the test could not separate.
- Groups with no bar joining them differ.
- Callout 1: A thick bar: ranks too close to separate.
- Callout 2: A group and its mean rank.
- Callout 3: The rank axis.
Watch out
- It compares ranks, not sizes: a group can rank first by a tiny margin.
Defaults
No settings: the chart draws one way.
Pinned in the code
- Draws the engine's numbers as given (precomputed by the Python or R analysis); the chart computes nothing statistical.
- Groups are placed at their mean rank from the joint ranking; the lower half is labelled on the left and the upper half on the right (Demšar 2006).
- A bar joins every set of groups that share a compact letter — groups joined by a bar are not significantly different at α under the chosen post hoc test.
- Bars are packed into lanes so they never overlap; their order carries no meaning.
# Critical-difference diagram — Codesplash Chart Lab (recipe "critical-difference")
# controls: defaults
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("critical-difference-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["arm"] = pd.Categorical(df["arm"].astype("string"), categories=["Placebo", "Low dose", "Mid dose", "High dose", "Max dose", "Active control"])
_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 letter_bars(labels, ranks, letters):
"""One bar per letter: the rank span of the groups whose letters include it."""
bars = []
for ch in sorted(set("".join(letters))):
rs = [r for r, l in zip(ranks, letters) if ch in l]
if len(rs) > 1:
bars.append((ch, min(rs), max(rs)))
return bars
LABEL = "arm"
R = "mean rank"
LET = "letters"
d = df.dropna(subset=[LABEL, R]).sort_values(R).reset_index(drop=True)
bars = letter_bars(d[LABEL].astype(str), d[R].tolist(), d[LET].astype(str).tolist())
fig, ax = plt.subplots(figsize=(8, 0.4 * (len(d) + len(bars)) + 1.4))
y = np.arange(len(d))[::-1] + len(bars) + 1
ax.scatter(d[R], y, s=40, color=PALETTE[0], zorder=3)
for yi, (_, row) in zip(y, d.iterrows()):
ax.plot([row[R], row[R]], [0.5, yi], color=GREY, linewidth=0.8, zorder=1)
ax.annotate(f"{row[LABEL]} ({row[LET]})", (row[R], yi), xytext=(6, 0), textcoords="offset points", va="center", fontsize=9)
for k, (ch, lo, hi) in enumerate(bars): # groups joined by a bar are not separated by the test
ax.plot([lo, hi], [k + 0.2, k + 0.2], color=REF, linewidth=4, solid_capstyle="round")
ax.set_yticks([])
ax.set_xlabel(R)
for side in ("left", "right", "top"):
ax.spines[side].set_visible(False)
ax.margins(x=0.15)
plt.show()Needs pandas, numpy, matplotlib · reads critical-difference-demo.csv · app theme from the optional codesplash helper
# Critical-difference diagram — Codesplash Chart Lab (recipe "critical-difference")
# controls: defaults
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("critical-difference-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["arm"] = pd.Categorical(df["arm"].astype("string"), categories=["Placebo", "Low dose", "Mid dose", "High dose", "Max dose", "Active control"])
_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 letter_bars(labels, ranks, letters):
"""One bar per letter: the rank span of the groups whose letters include it."""
bars = []
for ch in sorted(set("".join(letters))):
rs = [r for r, l in zip(ranks, letters) if ch in l]
if len(rs) > 1:
bars.append((ch, min(rs), max(rs)))
return bars
LABEL = "arm"
R = "mean rank"
LET = "letters"
d = df.dropna(subset=[LABEL, R]).sort_values(R).reset_index(drop=True)
bars = letter_bars(d[LABEL].astype(str), d[R].tolist(), d[LET].astype(str).tolist())
y = np.arange(len(d))[::-1] + len(bars) + 1
fig = go.Figure()
for yi, (_, row) in zip(y, d.iterrows()):
fig.add_scatter(x=[row[R], row[R]], y=[0.5, yi], mode="lines", line=dict(color=GREY, width=1), showlegend=False, hoverinfo="skip")
fig.add_scatter(x=d[R], y=y, mode="markers+text", marker=dict(size=9, color=PALETTE[0]), text=[f"{a} ({b})" for a, b in zip(d[LABEL], d[LET])],
textposition="middle right", showlegend=False)
for k, (ch, lo, hi) in enumerate(bars):
fig.add_scatter(x=[lo, hi], y=[k + 0.2, k + 0.2], mode="lines", line=dict(color=REF, width=5), name=ch, showlegend=False)
fig.update_yaxes(visible=False)
fig.update_xaxes(title=R)
fig.show()Needs pandas, numpy, plotly · reads critical-difference-demo.csv · app theme from the optional codesplash helper
# Critical-difference diagram — Codesplash Chart Lab (recipe "critical-difference")
# controls: defaults
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("critical-difference-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["arm"]] <- factor(df[["arm"]], levels = c("Placebo", "Low dose", "Mid dose", "High dose", "Max dose", "Active control"))
df[["letters"]] <- factor(df[["letters"]])
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
label_col <- "arm"
r_col <- "mean rank"
let_col <- "letters"
d <- df[!is.na(df[[label_col]]) & !is.na(df[[r_col]]), ]
d <- data.frame(lab = as.character(d[[label_col]]), r = d[[r_col]], let = as.character(d[[let_col]]))
d <- d[order(d$r), ]
chars <- sort(unique(unlist(strsplit(d$let, ""))))
bars <- do.call(rbind, lapply(chars, function(ch) { rs <- d$r[grepl(ch, d$let, fixed = TRUE)]; if (length(rs) > 1) data.frame(ch = ch, lo = min(rs), hi = max(rs)) else NULL }))
nb <- if (is.null(bars)) 0 else nrow(bars)
d$y <- rev(seq_len(nrow(d))) + nb + 1
if (nb) bars$y <- seq_len(nb) - 1 + 0.2 # groups joined by a bar are not separated by the test
p <- ggplot(d, aes(r, y)) + geom_segment(aes(xend = r, y = 0.5, yend = y), colour = grey_col) + geom_point(size = 2.6, colour = cs_cat[1]) +
geom_text(aes(label = paste0(lab, " (", let, ")")), hjust = -0.15, size = 3.2) +
{ if (nb) geom_segment(data = bars, aes(x = lo, xend = hi, y = y, yend = y), inherit.aes = FALSE, linewidth = 2, colour = ref_col, lineend = "round") } +
scale_x_continuous(expand = expansion(mult = c(0.08, 0.25))) + labs(x = r_col, y = NULL) + theme_cs +
theme(axis.text.y = element_blank(), axis.ticks.y = element_blank(), panel.grid.major.y = element_blank())
print(p)Needs ggplot2 · reads critical-difference-demo.csv · app theme from the optional codesplashr helper