svgagreement-chart
Agreement chart
Where do two raters agree, and where do they part?
How to read it
- Read each rectangle's width and height as the two raters' totals for that category.
- Dark squares are exact agreement: the larger the share of the rectangle, the better.
- Lighter areas are one step off; a rectangle far from square means the raters use that category differently.
- Callout 1: Exact agreement for the first category.
- Callout 2: A lighter band: one step off.
- 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
# Agreement chart — Codesplash Chart Lab (recipe "agreement-chart")
# controls: partial=true
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("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 = go.Figure()
for i, k in enumerate(levels):
fig.add_shape(type="rect", x0=xs[i], y0=ys[i], x1=xs[i] + rows[i], y1=ys[i] + cols[i], fillcolor="rgba(120,120,120,0.2)", line=dict(color=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)
fig.add_shape(type="rect", x0=xs[i], y0=ys[i], x1=xs[i] + pw, y1=ys[i] + ph, fillcolor=PALETTE[0], opacity=0.3, line_width=0)
ox, oy = (m[i, i - 1], m[i - 1, i]) if i else (0, 0)
fig.add_shape(type="rect", x0=xs[i] + ox, y0=ys[i] + oy, x1=xs[i] + ox + agree[i], y1=ys[i] + oy + agree[i], fillcolor=PALETTE[0], line_width=0)
fig.add_scatter(x=(xs[:-1] + rows / 2), y=(ys[:-1] + cols / 2), mode="text", text=levels, showlegend=False)
fig.update_layout(title=f"Bangdiwala's B = {B_stat:.3f}", xaxis=dict(title=A, range=[0, n]), yaxis=dict(title=B, range=[0, n], scaleanchor="x"))
fig.show()Needs pandas, numpy, plotly · reads agreement-chart-demo.csv · app theme from the optional codesplash helper
# Agreement chart — Codesplash Chart Lab (recipe "agreement-chart")
# controls: partial=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("agreement-chart-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["rater A"]] <- factor(df[["rater A"]], levels = c("low", "medium", "high", "severe"))
df[["rater B"]] <- factor(df[["rater B"]], levels = c("low", "medium", "high", "severe"))
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
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
A <- "rater A"
B <- "rater B"
N <- NULL
lv <- unique(c(levels_of(df[[A]]), levels_of(df[[B]])))
w <- if (is.null(N)) rep(1, nrow(df)) else df[[N]]
m <- xtabs(w ~ factor(as.character(df[[A]]), levels = lv) + factor(as.character(df[[B]]), levels = lv))
rows <- rowSums(m); cols <- colSums(m); agree <- diag(m); n <- sum(m); k <- length(lv)
B_stat <- sum(agree^2) / sum(rows * cols) # Bangdiwala's B
xs <- c(0, cumsum(rows))[seq_len(k)]; ys <- c(0, cumsum(cols))[seq_len(k)] # corner to corner
ox <- c(0, m[cbind(2:k, 1:(k - 1))]); oy <- c(0, m[cbind(1:(k - 1), 2:k)])
pw <- ox + agree + c(m[cbind(1:(k - 1), 2:k)], 0); ph <- oy + agree + c(m[cbind(2:k, 1:(k - 1))], 0)
rects <- data.frame(level = lv, x = xs, y = ys, w = rows, h = cols, ox = ox, oy = oy, a = agree, pw = pw, ph = ph)
p <- ggplot(rects) +
geom_rect(aes(xmin = x, xmax = x + w, ymin = y, ymax = y + h), fill = grey_col, alpha = 0.25, colour = ref_col) +
geom_rect(aes(xmin = x, xmax = x + pw, ymin = y, ymax = y + ph), fill = cs_cat[[1]], alpha = 0.3) +
geom_rect(aes(xmin = x + ox, xmax = x + ox + a, ymin = y + oy, ymax = y + oy + a), fill = cs_cat[[1]]) +
geom_text(aes(x, y + h, label = level), hjust = -0.1, vjust = 1.3, size = 2.8) +
coord_equal(xlim = c(0, n), ylim = c(0, n), expand = FALSE) +
labs(x = A, y = B, subtitle = sprintf("Bangdiwala's B = %.3f", B_stat)) + theme_cs
print(p)Needs ggplot2 · reads agreement-chart-demo.csv · app theme from the optional codesplashr helper