Skip to content
svgagreement-chart

Agreement chart

Where do two raters agree, and where do they part?

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

How to read it

  1. Read each rectangle's width and height as the two raters' totals for that category.
  2. Dark squares are exact agreement: the larger the share of the rectangle, the better.
  3. Lighter areas are one step off; a rectangle far from square means the raters use that category differently.
  1. Callout 1: Exact agreement for the first category.
  2. Callout 2: A lighter band: one step off.
  3. Callout 3: Bangdiwala's B: 1 is perfect agreement.

Watch out

  • Like kappa, it depends on how common each category is. Compare with the raw table.

Defaults

One step off
On
Shade neighbouring categories, for ordered scales.

Pinned in the code

  • The square has side n. Each category's rectangle is (A's total) × (B's total), placed corner to corner along the diagonal.
  • B = Σ nᵢᵢ² / Σ nᵢ₊n₊ᵢ: the agreement squares' area over the rectangles' area. Perfect agreement gives 1.
  • Levels follow the rater columns' order, so an ordered scale runs along the diagonal.
# Agreement chart — Codesplash Chart Lab (recipe "agreement-chart")
# controls: partial=true
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("agreement-chart-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["rater A"] = pd.Categorical(df["rater A"].astype("string"), categories=["low", "medium", "high", "severe"])
df["rater B"] = pd.Categorical(df["rater B"].astype("string"), categories=["low", "medium", "high", "severe"])

_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)))
A = "rater A"
B = "rater B"
N = None
d = df.dropna(subset=[A, B]).assign(_n=lambda f: f[N].astype(float) if N else 1.0)
levels = list(dict.fromkeys(levels_of(d[A]) + levels_of(d[B])))
tab = d.pivot_table(index=d[A].astype(str), columns=d[B].astype(str), values="_n", aggfunc="sum", fill_value=0).reindex(index=levels, columns=levels, fill_value=0)
n, rows, cols = tab.to_numpy().sum(), tab.sum(axis=1).to_numpy(), tab.sum(axis=0).to_numpy()
agree = np.diag(tab.to_numpy())
B_stat = (agree**2).sum() / (rows * cols).sum()  # Bangdiwala's B
xs, ys = np.r_[0, np.cumsum(rows)], np.r_[0, np.cumsum(cols)]  # rectangles run corner to corner
m = tab.to_numpy()
fig, ax = plt.subplots(figsize=(5.5, 5.5))
for i, k in enumerate(levels):
    ax.add_patch(plt.Rectangle((xs[i], ys[i]), rows[i], cols[i], facecolor=GREY, alpha=0.25, edgecolor=REF))
    pw = (m[i, i - 1] if i else 0) + m[i, i] + (m[i, i + 1] if i + 1 < len(levels) else 0)
    ph = (m[i - 1, i] if i else 0) + m[i, i] + (m[i + 1, i] if i + 1 < len(levels) else 0)
    ax.add_patch(plt.Rectangle((xs[i], ys[i]), pw, ph, facecolor=PALETTE[0], alpha=0.3))
    ox, oy = (m[i, i - 1], m[i - 1, i]) if i else (0, 0)
    ax.add_patch(plt.Rectangle((xs[i] + ox, ys[i] + oy), agree[i], agree[i], facecolor=PALETTE[0]))
    ax.text(xs[i] + 0.01 * n, ys[i] + cols[i] - 0.03 * n, k, fontsize=8)
ax.set_xlim(0, n)
ax.set_ylim(0, n)
ax.set_aspect("equal")
ax.set_xlabel(A)
ax.set_ylabel(B)
ax.set_title(f"Bangdiwala's B = {B_stat:.3f}", fontsize=10)
plt.show()

Needs pandas, numpy, matplotlib · reads agreement-chart-demo.csv · app theme from the optional codesplash helper