svggroup-metrics
Metrics by group (fairness)
Do a model's decisions or error rates differ across groups, and by how much?
How to read it
- Read one panel per metric with each group's value and interval.
- Check the largest gap in the title.
- Use the tolerance band: is a difference larger than you can accept?
- Callout 1: The largest gap on this metric.
- Callout 2: One group's value.
- 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
# 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 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
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_MARKERS = ["circle", "square", "triangle-up", "diamond", "cross", "star", "y-up", "triangle-down"]
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"])
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"
d = df.dropna(subset=[G, V]).copy()
kw = dict(error_x=d[HI] - d[V], error_x_minus=d[V] - d[LO]) if LO and HI else {}
fig = px.scatter(d, x=V, y=G, color=G, symbol=G, symbol_sequence=SERIES_MARKERS, facet_col=M, color_discrete_sequence=PALETTE, category_orders={G: levels_of(d[G]), M: levels_of(d[M])}, **kw) # marker shape per group, as in the app
fig.update_traces(marker_size=10, showlegend=False)
fig.update_xaxes(matches=None)
fig.show()Needs pandas, numpy, plotly · reads group-metrics-demo.csv · app theme from the optional codesplash helper
# Metrics by group (fairness) — Codesplash Chart Lab (recipe "group-metrics")
# controls: reference=0, band_low=0, band_high=0
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))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_shapes <- c(16, 15, 17, 18, 3, 8, 4, 25)
df <- read.csv("group-metrics-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["group"]] <- factor(df[["group"]], levels = c("Group A", "Group B", "Group C", "Group D"))
df[["metric"]] <- factor(df[["metric"]], levels = c("selection rate", "true positive rate", "false positive rate"))
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)]))
g_col <- "group"
m_col <- "metric"
v_col <- "value"
lo_col <- "ci_low"
hi_col <- "ci_high"
reference <- 0
d <- data.frame(g = factor(as.character(df[[g_col]]), levels = rev(levels_of(df[[g_col]]))), m = factor(as.character(df[[m_col]]), levels = levels_of(df[[m_col]])), v = df[[v_col]],
lo = if (is.null(lo_col)) NA_real_ else df[[lo_col]], hi = if (is.null(hi_col)) NA_real_ else df[[hi_col]])
p <- ggplot(d, aes(v, g, colour = g, shape = g)) + # marker shape per group, as in the app
{ if (!is.null(reference)) geom_vline(xintercept = reference, colour = ref_col, linetype = "dashed") } +
geom_errorbar(aes(xmin = lo, xmax = hi), orientation = "y", width = 0, linewidth = 0.8, na.rm = TRUE) + geom_point(size = 2.6) +
facet_wrap(~m, scales = "free_x") + scale_colour_manual(values = rev(cs_cat[seq_len(nlevels(d$g))]), guide = "none") +
scale_shape_manual(values = rev(rep_len(cs_shapes, nlevels(d$g))), guide = "none") +
labs(x = v_col, y = NULL) + theme_cs
print(p)Needs ggplot2 · reads group-metrics-demo.csv · app theme from the optional codesplashr helper