Skip to content
svgassoc-matrix

Association matrix

Which variables of any type are related, and how strongly?

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

How to read it

  1. Each cell is a strength between 0 and 1; the scale ignores direction.
  2. Check the note at the bottom: the measure depends on the column types.
  3. Use it to shortlist pairs, then look at each pair with a suited chart.
  1. Callout 1: A dark cell: a strong association.
  2. Callout 2: Which measure each kind of pair uses.
  3. Callout 3: Colour bar: from 0 to 1.

Watch out

  • Different measures aren't strictly comparable: a V of 0.3 and an r of 0.3 don't mean the same thing.

Defaults

Numeric pairs
|Pearson r|
Whether numeric pairs use Pearson or Spearman.
Also: |Spearman ρ|
Cluster order
Off
Reorder rows and columns so similar variables sit together.
Cells
Full matrix
Show the whole matrix or only its lower triangle.
Also: Lower triangle
Values in cells
On
Print the number in each cell.

Pinned in the code

  • Numeric × numeric: |Pearson r| (or |Spearman ρ|); categorical × categorical: Cramér's V with the Bergsma (2013) bias correction; numeric × categorical: correlation ratio η = √(SS_between / SS_total).
  • All over pairwise-complete rows (n in each tooltip); booleans count as categorical; every measure lies in [0, 1] so one sequential ramp fits.
  • The measures are not on a common scale of “effect”: compare within a measure, and treat this as a screening view (the profiler's association matrix).
# Association matrix — Codesplash Chart Lab (recipe "assoc-matrix")
# controls: numeric=pearson, cluster=false, triangle=full, values=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats
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("assoc-matrix-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["segment"] = pd.Categorical(df["segment"].astype("string"), categories=["Consumer", "SMB", "Enterprise"])
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")
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 cramers_v(a, b):
    """Bias-corrected Cramér's V (Bergsma 2013) over rows with both values."""
    t = pd.crosstab(a, b)
    n = t.to_numpy().sum()
    r, k = t.shape
    if n == 0 or r < 2 or k < 2:
        return np.nan
    chi2 = stats.chi2_contingency(t, correction=False)[0]
    phi2 = max(0.0, chi2 / n - (r - 1) * (k - 1) / (n - 1))
    rc, kc = r - (r - 1) ** 2 / (n - 1), k - (k - 1) ** 2 / (n - 1)
    den = min(rc - 1, kc - 1)
    return np.sqrt(phi2 / den) if den > 0 else np.nan

def eta(y, g):
    """Correlation ratio η = √(SS_between / SS_total)."""
    d = pd.DataFrame({"y": y, "g": g}).dropna()
    if len(d) < 3 or d["g"].nunique() < 2:
        return np.nan
    m = d["y"].mean()
    ssb = d.groupby("g", observed=True)["y"].agg(lambda s: len(s) * (s.mean() - m) ** 2).sum()
    sst = ((d["y"] - m) ** 2).sum()
    return np.sqrt(ssb / sst) if sst > 0 else np.nan

def association(a, b, numeric_method):
    both = pd.DataFrame({"a": a, "b": b}).dropna()  # pairwise-complete rows
    na, nb = a.name in NUMERIC, b.name in NUMERIC
    if na and nb:
        return abs(both["a"].corr(both["b"], method=numeric_method)) if len(both) > 2 else np.nan
    if na:
        return eta(both["a"], both["b"].astype(str))
    if nb:
        return eta(both["b"], both["a"].astype(str))
    return cramers_v(both["a"].astype(str), both["b"].astype(str))

VARS = ["income_k", "monthly_spend", "tenure_months", "age", "segment", "plan", "region", "churned"]
NUMERIC = set(["income_k", "monthly_spend", "tenure_months", "age"])  # booleans count as categorical
m = pd.DataFrame([[1.0 if a == b else association(df[a], df[b], "pearson") for b in VARS] for a in VARS], index=VARS, columns=VARS)
mask = None
fig, ax = plt.subplots(figsize=(1 + 0.6 * len(VARS), 0.8 + 0.5 * len(VARS)))
sns.heatmap(m, ax=ax, mask=mask, vmin=0, vmax=1, cmap=LinearSegmentedColormap.from_list("seq", SEQ), square=True, linewidths=0.5,
            annot=True, fmt=".2f", annot_kws={"fontsize": 8}, cbar_kws={"label": "|r|, Cramér's V or η", "shrink": 0.7})
ax.grid(False)
plt.show()

Needs pandas, numpy, matplotlib, scipy, seaborn · reads assoc-matrix-demo.csv · app theme from the optional codesplash helper

  • Geometry SQL is not emitted for the mixed-type matrix (Cramér's V and η need per-pair contingency tables); the numeric pairs match the correlation-heatmap SQL.