Skip to content
svggroup-metrics

Metrics by group (fairness)

Do a model's decisions or error rates differ across groups, and by how much?

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

How to read it

  1. Read one panel per metric with each group's value and interval.
  2. Check the largest gap in the title.
  3. Use the tolerance band: is a difference larger than you can accept?
  1. Callout 1: The largest gap on this metric.
  2. Callout 2: One group's value.
  3. Callout 3: The reference line.

Watch out

  • Fairness metrics can't all be equal at once when base rates differ: choose by purpose.

Defaults

Reference line (null = none)
0
Draw a line at a value you want to compare with.
Range -1,000,000,000 to 1,000,000,000, step 0.01
Tolerance band lower (equal bounds = none)
0
The lower end of the differences you would accept.
Range -1,000,000,000 to 1,000,000,000, step 0.01
Tolerance band upper
0
The upper end of the differences you would accept.
Range -1,000,000,000 to 1,000,000,000, step 0.01

Pinned in the code

  • Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
  • Gap = largest minus smallest group value per metric (demographic parity difference for selection rate, equal-opportunity difference for TPR); the engine reports ratios and equalized-odds differences in its table.
  • Panels on [0, 1] when every value is a rate; intervals are the engine's bootstrap CIs (shared random stream).
# Metrics by group (fairness) — Codesplash Chart Lab (recipe "group-metrics")
# controls: reference=0, band_low=0, band_high=0
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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_MARKERS = ["o", "s", "^", "D", "P", "*", "2", "v"]

df = pd.read_csv("group-metrics-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["group"] = pd.Categorical(df["group"].astype("string"), categories=["Group A", "Group B", "Group C", "Group D"])
df["metric"] = pd.Categorical(df["metric"].astype("string"), categories=["selection rate", "true positive rate", "false positive rate"])

_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)))
G = "group"
M = "metric"
V = "value"
LO = "ci_low"
HI = "ci_high"
REFERENCE, BAND = 0, (0, 0)
metrics, groups = levels_of(df[M]), levels_of(df[G])
fig, axes = plt.subplots(1, len(metrics), figsize=(3.2 * len(metrics) + 1.5, 3.6), sharey=True, squeeze=False)
for ax, m in zip(axes[0], metrics):
    d = df[df[M].astype(str) == str(m)]
    d = d.set_index(d[G].astype(str)).reindex([str(g) for g in groups])
    y = np.arange(len(groups))[::-1]
    if None not in BAND and BAND[1] > BAND[0]: ax.axvspan(*BAND, color="#19966e", alpha=0.1, lw=0)
    if REFERENCE is not None: ax.axvline(REFERENCE, color=REF, linestyle="--", linewidth=1)
    if LO and HI: ax.hlines(y, d[LO], d[HI], colors=PALETTE[: len(groups)], linewidth=2)
    for j in range(len(groups)):  # marker shape per group, as in the app
        ax.scatter(d[V].iloc[j], y[j], color=PALETTE[j % len(PALETTE)], marker=SERIES_MARKERS[j % 8], s=36, zorder=3)
    ax.set_title(f"{m} · gap {d[V].max() - d[V].min():.3f}", fontsize=10, loc="left")
axes[0, 0].set_yticks(np.arange(len(groups))[::-1], [str(g) for g in groups])
plt.show()

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