Skip to content
svgcritical-difference

Critical-difference diagram

How do the groups rank, and which rank differences are not significant?

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

How to read it

  1. Read the top axis as mean rank.
  2. A thick bar joins groups whose ranks the test could not separate.
  3. Groups with no bar joining them differ.
  1. Callout 1: A thick bar: ranks too close to separate.
  2. Callout 2: A group and its mean rank.
  3. 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