Skip to content
svgnullity-corr

Nullity correlation

Which columns tend to be missing together?

Demo data · seed 20261101 · 600 rows · default settings · 640 × 360SVG, lightSVG, darkDemo CSV

How to read it

  1. Each cell is the correlation between two columns' missing-value indicators.
  2. A dark cell: these two columns go missing together.
  3. Read clusters as groups of fields collected or lost together.
  1. Callout 1: A dark cell: the two columns go missing together.
  2. 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