svgmissing-matrix
Missing-value matrix
Where are the gaps, and do columns go missing together?
How to read it
- Read rows as data rows and columns as data columns; gaps are blank.
- Look for columns with many gaps, listed at the bottom.
- Blanks lining up across columns mean those values go missing together.
- Callout 1: A column with many gaps.
- Callout 2: How complete each row is.
- Callout 3: The missing share of each column.
Watch out
- Row order matters: sort it by a date or group to see whether gaps cluster.
Defaults
- Sort rows by completeness
- Off
- Move the most complete rows together, so patterns stand out.
Pinned in the code
- Missing = SQL NULL or NaN; present cells are filled, missing cells are blank.
- Rows keep their table order unless sorted (fewest missing first, stable).
- n > 400 rows: ⌈n/400⌉ consecutive rows per band; a band's blank opacity is its share of missing cells.
- Sparkline: share of non-missing columns per row (band mean), from the least to the most complete row.
# Missing-value matrix — Codesplash Chart Lab (recipe "missing-matrix")
# controls: sort=false
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-matrix-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["region"] = pd.Categorical(df["region"].astype("string"), categories=["North", "South", "East", "West"])
_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", "region", "income", "last_purchase", "satisfaction", "nps", "comments"]
miss = df[COLS].isna().to_numpy() # missing = NULL or not-a-number (pandas isna() covers both)
# rows keep their table order
per = int(np.ceil(len(miss) / 400)) if len(miss) > 400 else 1 # pool rows into ≤ 400 bands
band = np.arange(len(miss)) // per
share = pd.DataFrame(miss).groupby(band).mean().to_numpy() # missing share per band × column
completeness = 1 - share.mean(axis=1)
fig, (ax, spark) = plt.subplots(1, 2, figsize=(9, 5), gridspec_kw={"width_ratios": [8, 1], "wspace": 0.05}, sharey=True)
ax.imshow(1 - share, aspect="auto", cmap=LinearSegmentedColormap.from_list("present", ["white", PALETTE[0]]), vmin=0, vmax=1, interpolation="nearest") # present filled, missing blank
ax.set_xticks(range(len(COLS)), [f"{n}\n{s:.0%}" for n, s in zip(COLS, miss.mean(axis=0))], rotation=60, ha="right", fontsize=7)
ax.set_ylabel(f"rows{f' (bands of {per})' if per > 1 else ''}")
ax.grid(False)
spark.plot(completeness, np.arange(len(completeness)), color=REF, linewidth=1) # share of non-missing columns per row
spark.set_xlim(0, 1)
spark.set_xlabel("complete", fontsize=8)
spark.grid(False)
plt.show()Needs pandas, numpy, matplotlib · reads missing-matrix-demo.csv · app theme from the optional codesplash helper
# Missing-value matrix — Codesplash Chart Lab (recipe "missing-matrix")
# controls: sort=false
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-matrix-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["region"] = pd.Categorical(df["region"].astype("string"), categories=["North", "South", "East", "West"])
COLS = ["age", "region", "income", "last_purchase", "satisfaction", "nps", "comments"]
miss = df[COLS].isna().to_numpy()
per = int(np.ceil(len(miss) / 400)) if len(miss) > 400 else 1
share = pd.DataFrame(miss).groupby(np.arange(len(miss)) // per).mean().to_numpy()
fig = go.Figure(go.Heatmap(z=1 - share, x=[f"{n} ({s:.0%})" for n, s in zip(COLS, miss.mean(axis=0))], colorscale=[[0, "white"], [1, PALETTE[0]]], zmin=0, zmax=1, colorbar_title="present"))
fig.update_layout(yaxis=dict(autorange="reversed", title=f"rows{f' (bands of {per})' if per > 1 else ''}"))
fig.show()Needs pandas, numpy, plotly · reads missing-matrix-demo.csv · app theme from the optional codesplash helper
# Missing-value matrix — Codesplash Chart Lab (recipe "missing-matrix")
# controls: sort=false
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-matrix-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[["region"]] <- factor(df[["region"]], levels = c("North", "South", "East", "West"))
df[["comments"]] <- factor(df[["comments"]])
cols <- c("age", "region", "income", "last_purchase", "satisfaction", "nps", "comments")
miss <- sapply(df[cols], is.na) # NULL and not-a-number both count as missing
per <- if (nrow(miss) > 400) ceiling(nrow(miss) / 400) else 1 # pool rows into <= 400 bands
band <- (seq_len(nrow(miss)) - 1) %/% per
share <- rowsum(miss * 1, band) / as.vector(table(band))
cells <- data.frame(band = rep(as.integer(rownames(share)), ncol(share)), column = rep(cols, each = nrow(share)), present = 1 - as.vector(share))
cells$column <- factor(cells$column, levels = cols, labels = sprintf("%s (%.0f%%)", cols, 100 * colMeans(miss)))
p <- ggplot(cells, aes(column, band, fill = present)) +
geom_raster() +
scale_fill_gradient(low = "white", high = cs_cat[1], limits = c(0, 1)) +
scale_y_reverse() +
labs(x = NULL, y = if (per > 1) sprintf("rows (bands of %d)", per) else "rows") +
theme_cs + theme(axis.text.x = element_text(angle = 60, hjust = 1), panel.grid = element_blank())
print(p)Needs ggplot2 · reads missing-matrix-demo.csv · app theme from the optional codesplashr helper
-- Missing-value matrix — Codesplash Chart Lab (recipe "missing-matrix")
-- controls: sort=false
-- missing share per column in bands of ⌈n / 400⌉ consecutive rows (table order)
WITH r AS (SELECT row_number() OVER () - 1 AS i, * FROM read_csv('missing-matrix-demo.csv')),
p AS (SELECT CASE WHEN count(*) > 400 THEN ceil(count(*) / 400) ELSE 1 END AS per FROM r)
SELECT i // per AS band,
avg(("age" IS NULL)::INTEGER) AS "age",
avg(("region" IS NULL)::INTEGER) AS "region",
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 r, p
GROUP BY ALL
ORDER BY band;Needs duckdb · reads missing-matrix-demo.csv