svgmissing-by-group
Missing by group
Does missingness depend on a group (a hint that data are not missing completely at random)?
How to read it
- Read a cell as the share missing in that column within that group.
- Compare a row across groups: differences suggest missingness depends on the group.
- Check the group sizes in the headers before reading small groups.
- Callout 1: This column's missing share in one group.
- Callout 2: A row that differs across groups: not missing completely at random.
- Callout 3: The group's size.
Watch out
- Depending on an observed group doesn't rule out dependence on unobserved values too.
Defaults
No settings: the chart draws one way.
Pinned in the code
- Cell = missing rows / rows in the group; a missing group value forms its own “(missing)” column.
- Groups: declared level order, else by frequency; at most 10 (plus “(missing)”).
- Colour scales to the largest share in the table (at least 5 %), so small differences stay visible; the printed % is exact.
- A pattern that differs by group is evidence against MCAR — confirm with Little's MCAR test (Analyze → Missing-data patterns).
# Missing by group — Codesplash Chart Lab (recipe "missing-by-group")
# controls: defaults
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
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("missing-by-group-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["last_purchase"] = pd.to_datetime(df["last_purchase"])
df["plan"] = pd.Categorical(df["plan"].astype("string"), categories=["Basic", "Plus", "Pro"])
_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")
COLS = ["age", "income", "last_purchase", "satisfaction", "nps", "comments"]
g = df["plan"].astype(object).where(df["plan"].notna(), "(missing)").astype(str) # a missing group value forms its own column
groups = [l for l in ["Basic", "Plus", "Pro"] if l in set(g)][:10] # declared level order
groups += ["(missing)"] if (g == "(missing)").any() else []
share = df[COLS].isna().groupby(g).mean().T.reindex(columns=groups) # missing rows / rows in the group
n = g.value_counts().reindex(groups)
vmax = max(0.05, float(share.max().max())) # colour scales to the largest share (at least 5 %)
fig, ax = plt.subplots(figsize=(1.5 + 0.9 * len(groups), 0.8 + 0.45 * len(COLS)))
ax.imshow(share.to_numpy(), cmap=LinearSegmentedColormap.from_list("seq", SEQ), vmin=0, vmax=vmax, aspect="auto")
for i in range(share.shape[0]):
for j in range(share.shape[1]):
ax.text(j, i, f"{share.iat[i, j]:.0%}", ha="center", va="center", fontsize=7, color="white" if share.iat[i, j] > vmax * 0.6 else "black")
ax.set_xticks(range(len(groups)), [f"{l}\nn = {n[l]:,}" for l in groups], fontsize=8)
ax.set_yticks(range(len(COLS)), COLS, fontsize=8)
ax.set_title("Missing share by plan", fontsize=10, loc="left")
ax.grid(False)
plt.show()Needs pandas, numpy, matplotlib · reads missing-by-group-demo.csv · app theme from the optional codesplash helper
# Missing by group — Codesplash Chart Lab (recipe "missing-by-group")
# controls: defaults
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("missing-by-group-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["last_purchase"] = pd.to_datetime(df["last_purchase"])
df["plan"] = pd.Categorical(df["plan"].astype("string"), categories=["Basic", "Plus", "Pro"])
_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")
COLS = ["age", "income", "last_purchase", "satisfaction", "nps", "comments"]
g = df["plan"].astype(object).where(df["plan"].notna(), "(missing)").astype(str) # a missing group value forms its own column
groups = [l for l in ["Basic", "Plus", "Pro"] if l in set(g)][:10] # declared level order
groups += ["(missing)"] if (g == "(missing)").any() else []
share = df[COLS].isna().groupby(g).mean().T.reindex(columns=groups)
fig = go.Figure(go.Heatmap(z=share.to_numpy(), x=groups, y=COLS, zmin=0, zmax=max(0.05, float(share.max().max())),
colorscale=[[0, SEQ[0]], [1, SEQ[-1]]], texttemplate="%{z:.0%}", colorbar_tickformat=".0%"))
fig.update_layout(title="Missing share by plan", yaxis_autorange="reversed")
fig.show()Needs pandas, numpy, plotly · reads missing-by-group-demo.csv · app theme from the optional codesplash helper
# Missing by group — Codesplash Chart Lab (recipe "missing-by-group")
# controls: defaults
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("missing-by-group-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["last_purchase"]] <- as.POSIXct(df[["last_purchase"]], tz = "UTC")
df[["comments"]] <- factor(df[["comments"]])
df[["plan"]] <- factor(df[["plan"]], levels = c("Basic", "Plus", "Pro"))
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
cols <- c("age", "income", "last_purchase", "satisfaction", "nps", "comments")
g <- ifelse(is.na(df[["plan"]]), "(missing)", as.character(df[["plan"]])) # a missing group value forms its own column
groups <- utils::head(intersect(c("Basic", "Plus", "Pro"), g), 10) # declared level order
if (any(g == "(missing)")) groups <- c(groups, "(missing)")
keep <- g %in% groups
share <- sapply(cols, function(cl) tapply(is.na(df[[cl]][keep]), g[keep], mean))[groups, , drop = FALSE]
cells <- data.frame(group = rep(groups, ncol(share)), column = rep(cols, each = length(groups)), share = as.vector(share))
cells$group <- factor(cells$group, levels = groups); cells$column <- factor(cells$column, levels = rev(cols))
p <- ggplot(cells, aes(group, column, fill = share)) +
geom_tile(colour = "white") +
geom_text(aes(label = sprintf("%.0f%%", 100 * share)), size = 2.8) +
scale_fill_gradient(low = seq_ramp[1], high = seq_ramp[2], limits = c(0, max(0.05, max(cells$share))), labels = function(v) sprintf("%.0f%%", 100 * v)) +
labs(x = NULL, y = NULL, title = "Missing share by plan") +
theme_cs + theme(panel.grid = element_blank())
print(p)Needs ggplot2 · reads missing-by-group-demo.csv · app theme from the optional codesplashr helper
-- Missing by group — Codesplash Chart Lab (recipe "missing-by-group")
-- controls: defaults
-- missing share per column within each group; a missing group value is its own group
SELECT coalesce("plan"::VARCHAR, '(missing)') AS "group", count(*) AS n,
avg(("age" IS NULL)::INTEGER) AS "age",
avg(("income" IS NULL)::INTEGER) AS "income",
avg(("last_purchase" IS NULL)::INTEGER) AS "last_purchase",
avg(("satisfaction" IS NULL)::INTEGER) AS "satisfaction",
avg(("nps" IS NULL)::INTEGER) AS "nps",
avg(("comments" IS NULL)::INTEGER) AS "comments"
FROM read_csv('missing-by-group-demo.csv')
GROUP BY ALL
ORDER BY n DESC;Needs duckdb · reads missing-by-group-demo.csv