svgupset
UpSet of missing patterns
Which combinations of columns are missing together, and how often?
How to read it
- Read a dot column as a combination of columns missing together.
- Read the bar above it as how many rows have that exact combination.
- Read the small bars at the left for each column's total.
- Callout 1: Height: rows with exactly this pattern.
- Callout 2: Joined dots: the columns missing together.
- Callout 3: Bars at the left: total missing per column.
Watch out
- Patterns beyond the top few are collapsed; the note counts how many were left out.
Defaults
- Patterns shown
- 12
- How many missing-value patterns to show, most common first.
- Range 3 to 30, step 1
Pinned in the code
- Each incomplete row counts once, under the exact set of columns it is missing (exclusive intersections, as in naniar `gg_miss_upset`).
- Patterns are ordered by row count (ties: fewer columns first); beyond the top k they are summarized in the footer.
- Set sizes on the left are the total missing count per column; complete rows are reported, not drawn.
- Bars for single-column patterns use the first palette colour, multi-column patterns the fifth.
# UpSet of missing patterns — Codesplash Chart Lab (recipe "upset")
# controls: top=12
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("upset-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() # missing = NULL or not-a-number
size = miss.sum()
used = sorted([c for c in COLS if size[c] > 0], key=lambda c: (-size[c], COLS.index(c))) # sets by missing count
key = miss[used].astype(int).astype(str).agg("".join, axis=1)
complete = int((~miss[used].any(axis=1)).sum())
counts = key[key.str.contains("1")].value_counts() # each incomplete row once, under its exact set
# order: row count, then fewer columns, then the key descending (the app's tie-break)
patterns = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0].count("1"), tuple(-int(ch) for ch in kv[0])))
top, rest = patterns[:12], patterns[12:]
fig = plt.figure(figsize=(9, 5))
gs = fig.add_gridspec(2, 2, width_ratios=(1, 4), height_ratios=(2, 1.3), hspace=0.05, wspace=0.45) # room for the set names
bars, matrix, sets = fig.add_subplot(gs[0, 1]), fig.add_subplot(gs[1, 1]), fig.add_subplot(gs[1, 0])
xs = np.arange(len(top))
colours = [PALETTE[0] if k.count("1") == 1 else PALETTE[4] for k, _ in top] # single-column vs multi-column patterns
bars.bar(xs, [n for _, n in top], color=colours)
bars.bar_label(bars.containers[0], fontsize=7)
bars.set_xticks([])
bars.set_ylabel("rows")
bars.set_title(f"{complete:,} complete rows" + (f" · {len(rest)} more patterns ({sum(n for _, n in rest):,} rows)" if rest else ""), fontsize=9, loc="left")
for j, (k, _) in enumerate(top):
on = [i for i, ch in enumerate(k) if ch == "1"]
matrix.scatter([j] * len(used), range(len(used)), s=40, color=GREY, zorder=2)
matrix.scatter([j] * len(on), on, s=40, color=REF, zorder=3)
if len(on) > 1:
matrix.plot([j, j], [min(on), max(on)], color=REF, linewidth=1.5, zorder=2)
matrix.set_yticks(range(len(used)), used, fontsize=8)
matrix.set_xticks([])
matrix.set_xlim(bars.get_xlim())
matrix.invert_yaxis()
matrix.grid(False)
sets.barh(range(len(used)), [size[c] for c in used], color=REF)
sets.set_ylim(matrix.get_ylim())
sets.invert_xaxis()
sets.set_yticks([])
sets.set_xlabel("missing", fontsize=8)
plt.show()Needs pandas, numpy, matplotlib · reads upset-demo.csv · app theme from the optional codesplash helper
# UpSet of missing patterns — Codesplash Chart Lab (recipe "upset")
# controls: top=12
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
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("upset-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() # missing = NULL or not-a-number
size = miss.sum()
used = sorted([c for c in COLS if size[c] > 0], key=lambda c: (-size[c], COLS.index(c))) # sets by missing count
key = miss[used].astype(int).astype(str).agg("".join, axis=1)
complete = int((~miss[used].any(axis=1)).sum())
counts = key[key.str.contains("1")].value_counts() # each incomplete row once, under its exact set
# order: row count, then fewer columns, then the key descending (the app's tie-break)
patterns = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0].count("1"), tuple(-int(ch) for ch in kv[0])))
top, rest = patterns[:12], patterns[12:]
fig = make_subplots(rows=2, cols=2, column_widths=[0.2, 0.8], row_heights=[0.6, 0.4], shared_xaxes="columns", shared_yaxes="rows", horizontal_spacing=0.01, vertical_spacing=0.02)
fig.add_bar(x=list(range(len(top))), y=[n for _, n in top], marker_color=[PALETTE[0] if k.count("1") == 1 else PALETTE[4] for k, _ in top], text=[n for _, n in top], showlegend=False, row=1, col=2)
for j, (k, _) in enumerate(top):
fig.add_scatter(x=[j] * len(used), y=used, mode="markers+lines", marker=dict(size=10, color=[REF if ch == "1" else GREY for ch in k]), line=dict(width=0), showlegend=False, row=2, col=2)
fig.add_bar(y=used, x=[size[c] for c in used], orientation="h", marker_color=REF, showlegend=False, row=2, col=1)
fig.update_xaxes(autorange="reversed", row=2, col=1)
fig.update_yaxes(autorange="reversed", row=2, col=2)
fig.update_layout(title=f"{complete:,} complete rows", height=520)
fig.show()Needs pandas, numpy, plotly · reads upset-demo.csv · app theme from the optional codesplash helper
# UpSet of missing patterns — Codesplash Chart Lab (recipe "upset")
# controls: top=12
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("upset-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"]])
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
arrange <- function(plots, layout, widths = NULL, heights = NULL) {
# layout: matrix of plot indices (NA = empty cell). patchwork aligns the panels when it is
# installed; otherwise base grid viewports place the plots (axes may not line up exactly).
widths <- if (is.null(widths)) rep(1, ncol(layout)) else widths
heights <- if (is.null(heights)) rep(1, nrow(layout)) else heights
if (requireNamespace("patchwork", quietly = TRUE)) {
design <- paste(apply(layout, 1, function(r) paste(ifelse(is.na(r), "#", LETTERS[r]), collapse = "")), collapse = "\n")
print(patchwork::wrap_plots(plots, design = design, widths = widths, heights = heights, guides = "collect"))
return(invisible())
}
grid::grid.newpage()
grid::pushViewport(grid::viewport(layout = grid::grid.layout(nrow(layout), ncol(layout),
widths = grid::unit(widths, "null"), heights = grid::unit(heights, "null"))))
for (i in seq_along(plots)) {
at <- which(layout == i, arr.ind = TRUE)
print(plots[[i]], vp = grid::viewport(layout.pos.row = unique(at[, 1]), layout.pos.col = unique(at[, 2])))
}
}
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
size <- colSums(miss)
used <- cols[size > 0][order(-size[size > 0], match(cols[size > 0], cols))] # sets by missing count
key <- apply(miss[, used, drop = FALSE] * 1, 1, paste, collapse = "")
complete <- sum(!grepl("1", key))
tab <- table(key[grepl("1", key)]) # each incomplete row once, under its exact set
pat <- data.frame(key = names(tab), n = as.vector(tab), stringsAsFactors = FALSE)
pat$k <- nchar(gsub("0", "", pat$key))
pat <- pat[order(-pat$n, pat$k, -xtfrm(pat$key)), ] # count, fewer columns, key descending
rest <- pat[-seq_len(min(12, nrow(pat))), ]
pat <- utils::head(pat, 12)
pat$x <- seq_len(nrow(pat))
dots <- do.call(rbind, lapply(seq_len(nrow(pat)), function(j) data.frame(x = j, set = used, on = strsplit(pat$key[j], "")[[1]] == "1")))
dots$set <- factor(dots$set, levels = rev(used))
bars <- ggplot(pat, aes(x, n, fill = k > 1)) + geom_col(show.legend = FALSE) +
geom_text(aes(label = n), vjust = -0.3, size = 2.6) +
scale_fill_manual(values = c(`FALSE` = cs_cat[1], `TRUE` = cs_cat[5])) + # single- vs multi-column patterns
scale_x_continuous(limits = c(0.5, nrow(pat) + 0.5)) +
labs(x = NULL, y = "rows", subtitle = sprintf("%d complete rows%s", complete, if (nrow(rest)) sprintf(" · %d more patterns (%d rows)", nrow(rest), sum(rest$n)) else "")) +
theme_cs + theme(axis.text.x = element_blank())
matrix <- ggplot(dots, aes(x, set)) +
geom_line(data = dots[dots$on, ], aes(group = x), colour = ref_col) +
geom_point(aes(colour = on), size = 2.6, show.legend = FALSE) +
scale_colour_manual(values = c(`FALSE` = grey_col, `TRUE` = ref_col)) +
scale_x_continuous(limits = c(0.5, nrow(pat) + 0.5)) +
labs(x = NULL, y = NULL) + theme_cs + theme(axis.text.x = element_blank(), panel.grid = element_blank())
sets <- ggplot(data.frame(set = factor(used, levels = rev(used)), n = size[used]), aes(n, set)) +
geom_col(fill = ref_col) + scale_x_reverse() + labs(x = "missing", y = NULL) +
theme_cs + theme(axis.text.y = element_blank())
arrange(list(bars, matrix, sets), layout = matrix(c(NA, 1, 3, 2), 2, byrow = TRUE), widths = c(1, 4), heights = c(2, 1.3))Needs ggplot2 · reads upset-demo.csv · app theme from the optional codesplashr helper
-- UpSet of missing patterns — Codesplash Chart Lab (recipe "upset")
-- controls: top=12
-- exclusive missing patterns: each incomplete row counted once under the exact set of missing columns
WITH p AS (
SELECT list_filter([CASE WHEN "age" IS NULL THEN 'age' END, CASE WHEN "region" IS NULL THEN 'region' END, CASE WHEN "income" IS NULL THEN 'income' END, CASE WHEN "last_purchase" IS NULL THEN 'last_purchase' END, CASE WHEN "satisfaction" IS NULL THEN 'satisfaction' END, CASE WHEN "nps" IS NULL THEN 'nps' END, CASE WHEN "comments" IS NULL THEN 'comments' END], lambda x: x IS NOT NULL) AS missing
FROM read_csv('upset-demo.csv')
)
SELECT missing, count(*) AS rows
FROM p
WHERE len(missing) > 0
GROUP BY missing
ORDER BY rows DESC, len(missing);Needs duckdb · reads upset-demo.csv