svgnullity-corr
Nullity correlation
Which columns tend to be missing together?
How to read it
- Each cell is the correlation between two columns' missing-value indicators.
- A dark cell: these two columns go missing together.
- Read clusters as groups of fields collected or lost together.
- Callout 1: A dark cell: the two columns go missing together.
- Callout 2: Colour legend: from −1 to 1.
Watch out
- Columns that are never or always missing have no correlation, so a blank cell doesn't mean unrelated.
Defaults
- Clustered order
- On
- Reorder rows and columns so columns missing together sit next to each other.
- Show r
- On
- Print the correlation in each cell.
- Lower triangle only
- Off
- Hide the mirror-image half of the matrix.
Pinned in the code
- Indicator I = 1 when a cell is missing (NULL/NaN); r is the Pearson correlation of indicators over all rows (= φ coefficient).
- Columns that are complete or entirely missing are left out (their indicator has no variance).
- Order: average-linkage clustering on 1 − |r| when clustered; otherwise column order.
- Diverging ramp centred at 0: +1 = always missing together, −1 = never missing together.
# Nullity correlation — Codesplash Chart Lab (recipe "nullity-corr")
# controls: cluster=true, values=true, lower=false
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
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("nullity-corr-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")
def cluster_order(m):
"""Leaf order of average-linkage clustering on 1 − |r| (the app's ordering; scipy's leaves differ)."""
d = 1 - np.abs(np.nan_to_num(np.asarray(m, dtype=float)))
clusters = [[i] for i in range(len(d))]
while len(clusters) > 1:
best, best_d = (0, 1), np.inf
for a in range(len(clusters)):
for b in range(a + 1, len(clusters)):
dist = d[np.ix_(clusters[a], clusters[b])].mean()
if dist < best_d:
best, best_d = (a, b), dist
a, b = best
merged = clusters[a] + clusters[b]
clusters = [cl for i, cl in enumerate(clusters) if i not in (a, b)] + [merged]
return clusters[0]
def apa_r(v):
return "" if np.isnan(v) else f"{v:.2f}".replace("0.", ".", 1).replace("-", "\u2212")
COLS = ["age", "region", "income", "last_purchase", "satisfaction", "nps", "comments", "churned"]
ind = df[COLS].isna().astype(float) # missing = NULL or not-a-number (pandas isna() covers both)
ind = ind.loc[:, (ind.sum() > 0) & (ind.sum() < len(ind))] # complete / all-missing columns have no variance
r = ind.corr() # Pearson on 0/1 indicators = φ
order = cluster_order(r.to_numpy())
r = r.iloc[order, order]
mask = None
fig, ax = plt.subplots(figsize=(1 + 0.6 * len(r), 0.8 + 0.5 * len(r)))
sns.heatmap(r, ax=ax, mask=mask, vmin=-1, vmax=1, center=0, cmap=LinearSegmentedColormap.from_list("div", DIV), square=True, linewidths=0.5,
annot=r.map(apa_r), fmt="", annot_kws={"fontsize": 8}, cbar_kws={"label": "nullity r", "shrink": 0.7})
ax.grid(False)
plt.show()Needs pandas, numpy, matplotlib, seaborn · reads nullity-corr-demo.csv · app theme from the optional codesplash helper
# Nullity correlation — Codesplash Chart Lab (recipe "nullity-corr")
# controls: cluster=true, values=true, lower=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("nullity-corr-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")
def cluster_order(m):
"""Leaf order of average-linkage clustering on 1 − |r| (the app's ordering; scipy's leaves differ)."""
d = 1 - np.abs(np.nan_to_num(np.asarray(m, dtype=float)))
clusters = [[i] for i in range(len(d))]
while len(clusters) > 1:
best, best_d = (0, 1), np.inf
for a in range(len(clusters)):
for b in range(a + 1, len(clusters)):
dist = d[np.ix_(clusters[a], clusters[b])].mean()
if dist < best_d:
best, best_d = (a, b), dist
a, b = best
merged = clusters[a] + clusters[b]
clusters = [cl for i, cl in enumerate(clusters) if i not in (a, b)] + [merged]
return clusters[0]
def apa_r(v):
return "" if np.isnan(v) else f"{v:.2f}".replace("0.", ".", 1).replace("-", "\u2212")
COLS = ["age", "region", "income", "last_purchase", "satisfaction", "nps", "comments", "churned"]
ind = df[COLS].isna().astype(float)
ind = ind.loc[:, (ind.sum() > 0) & (ind.sum() < len(ind))]
r = ind.corr()
order = cluster_order(r.to_numpy())
r = r.iloc[order, order]
fig = go.Figure(go.Heatmap(z=r.to_numpy(), x=list(r.columns), y=list(r.index), zmin=-1, zmax=1, colorscale=[[0, DIV[0]], [0.5, DIV[1]], [1, DIV[2]]],
text=r.map(apa_r).to_numpy(), texttemplate="%{text}", colorbar_title="nullity r"))
fig.update_layout(yaxis_autorange="reversed")
fig.show()Needs pandas, numpy, plotly · reads nullity-corr-demo.csv · app theme from the optional codesplash helper
# Nullity correlation — Codesplash Chart Lab (recipe "nullity-corr")
# controls: cluster=true, values=true, lower=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("nullity-corr-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[["churned"]] <- as.logical(df[["churned"]])
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
cluster_order <- function(m) {
# average linkage on 1 - |r|; merged clusters are appended last (the app's leaf order)
d <- 1 - abs(ifelse(is.na(m), 0, m))
clusters <- as.list(seq_len(nrow(d)))
while (length(clusters) > 1) {
best <- c(1, 2); best_d <- Inf
for (a in seq_len(length(clusters) - 1)) for (b in (a + 1):length(clusters)) {
dist <- mean(d[clusters[[a]], clusters[[b]]])
if (dist < best_d) { best <- c(a, b); best_d <- dist }
}
merged <- c(clusters[[best[1]]], clusters[[best[2]]])
clusters <- c(clusters[-best], list(merged))
}
clusters[[1]]
}
apa_r <- function(v) ifelse(is.na(v), "", gsub("-", "\u2212", sub("^(-?)0\\.", "\\1.", sprintf("%.2f", v))))
cols <- c("age", "region", "income", "last_purchase", "satisfaction", "nps", "comments", "churned")
ind <- sapply(df[cols], is.na) * 1 # 1 = missing (NULL or not-a-number)
ind <- ind[, colSums(ind) > 0 & colSums(ind) < nrow(ind), drop = FALSE] # drop complete / all-missing columns
r <- stats::cor(ind) # Pearson on indicators = φ
ord <- colnames(r)[cluster_order(r)]
cells <- expand.grid(row = ord, col = ord, stringsAsFactors = FALSE)
cells$r <- r[cbind(cells$row, cells$col)]
cells$row <- factor(cells$row, levels = rev(ord)); cells$col <- factor(cells$col, levels = ord)
p <- ggplot(cells, aes(col, row, fill = r)) +
geom_tile(colour = "white", linewidth = 0.5) +
geom_text(aes(label = apa_r(r)), size = 3) +
scale_fill_gradient2(low = div_ramp[1], mid = div_ramp[2], high = div_ramp[3], midpoint = 0, limits = c(-1, 1), name = "nullity r") +
coord_equal() + labs(x = NULL, y = NULL) +
theme_cs + theme(axis.text.x = element_text(angle = 45, hjust = 1), panel.grid = element_blank())
print(p)Needs ggplot2 · reads nullity-corr-demo.csv · app theme from the optional codesplashr helper
-- Nullity correlation — Codesplash Chart Lab (recipe "nullity-corr")
-- controls: cluster=true, values=true, lower=false
-- φ between missingness indicators for every pair (NULL when a column is complete or all missing)
SELECT 'age' AS a, 'region' AS b, corr(("age" IS NULL)::INTEGER, ("region" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'age' AS a, 'income' AS b, corr(("age" IS NULL)::INTEGER, ("income" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'age' AS a, 'last_purchase' AS b, corr(("age" IS NULL)::INTEGER, ("last_purchase" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'age' AS a, 'satisfaction' AS b, corr(("age" IS NULL)::INTEGER, ("satisfaction" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'age' AS a, 'nps' AS b, corr(("age" IS NULL)::INTEGER, ("nps" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'age' AS a, 'comments' AS b, corr(("age" IS NULL)::INTEGER, ("comments" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'age' AS a, 'churned' AS b, corr(("age" IS NULL)::INTEGER, ("churned" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'region' AS a, 'income' AS b, corr(("region" IS NULL)::INTEGER, ("income" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'region' AS a, 'last_purchase' AS b, corr(("region" IS NULL)::INTEGER, ("last_purchase" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'region' AS a, 'satisfaction' AS b, corr(("region" IS NULL)::INTEGER, ("satisfaction" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'region' AS a, 'nps' AS b, corr(("region" IS NULL)::INTEGER, ("nps" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'region' AS a, 'comments' AS b, corr(("region" IS NULL)::INTEGER, ("comments" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'region' AS a, 'churned' AS b, corr(("region" IS NULL)::INTEGER, ("churned" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'income' AS a, 'last_purchase' AS b, corr(("income" IS NULL)::INTEGER, ("last_purchase" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'income' AS a, 'satisfaction' AS b, corr(("income" IS NULL)::INTEGER, ("satisfaction" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'income' AS a, 'nps' AS b, corr(("income" IS NULL)::INTEGER, ("nps" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'income' AS a, 'comments' AS b, corr(("income" IS NULL)::INTEGER, ("comments" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'income' AS a, 'churned' AS b, corr(("income" IS NULL)::INTEGER, ("churned" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'last_purchase' AS a, 'satisfaction' AS b, corr(("last_purchase" IS NULL)::INTEGER, ("satisfaction" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'last_purchase' AS a, 'nps' AS b, corr(("last_purchase" IS NULL)::INTEGER, ("nps" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'last_purchase' AS a, 'comments' AS b, corr(("last_purchase" IS NULL)::INTEGER, ("comments" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'last_purchase' AS a, 'churned' AS b, corr(("last_purchase" IS NULL)::INTEGER, ("churned" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'satisfaction' AS a, 'nps' AS b, corr(("satisfaction" IS NULL)::INTEGER, ("nps" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'satisfaction' AS a, 'comments' AS b, corr(("satisfaction" IS NULL)::INTEGER, ("comments" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'satisfaction' AS a, 'churned' AS b, corr(("satisfaction" IS NULL)::INTEGER, ("churned" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'nps' AS a, 'comments' AS b, corr(("nps" IS NULL)::INTEGER, ("comments" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'nps' AS a, 'churned' AS b, corr(("nps" IS NULL)::INTEGER, ("churned" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'comments' AS a, 'churned' AS b, corr(("comments" IS NULL)::INTEGER, ("churned" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv');Needs duckdb · reads nullity-corr-demo.csv