svgassoc-matrix
Association matrix
Which variables of any type are related, and how strongly?
How to read it
- Each cell is a strength between 0 and 1; the scale ignores direction.
- Check the note at the bottom: the measure depends on the column types.
- Use it to shortlist pairs, then look at each pair with a suited chart.
- Callout 1: A dark cell: a strong association.
- Callout 2: Which measure each kind of pair uses.
- 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
# 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 plotly.express as px
import plotly.graph_objects as go
from scipy import stats
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("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"])
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)
fig = go.Figure(go.Heatmap(z=m.to_numpy(), x=list(m.columns), y=list(m.index), zmin=0, zmax=1, colorscale=[[0, SEQ[0]], [1, SEQ[-1]]],
texttemplate="%{z:.2f}", colorbar_title="assoc."))
fig.update_layout(yaxis_autorange="reversed", width=120 + 50 * len(VARS), height=100 + 45 * len(VARS))
fig.show()Needs pandas, numpy, plotly, scipy · reads assoc-matrix-demo.csv · app theme from the optional codesplash helper
# Association matrix — Codesplash Chart Lab (recipe "assoc-matrix")
# controls: numeric=pearson, cluster=false, triangle=full, values=true
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("assoc-matrix-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["churned"]] <- as.logical(df[["churned"]])
df[["segment"]] <- factor(df[["segment"]], levels = c("Consumer", "SMB", "Enterprise"))
df[["plan"]] <- factor(df[["plan"]], levels = c("Basic", "Plus", "Pro"))
df[["region"]] <- factor(df[["region"]])
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]]
}
cramers_v <- function(a, b) {
# bias-corrected Cramér's V (Bergsma 2013) over rows with both values
t <- table(a, b); n <- sum(t); r <- nrow(t); k <- ncol(t)
if (n == 0 || r < 2 || k < 2) return(NA_real_)
chi2 <- suppressWarnings(stats::chisq.test(t, correct = FALSE)$statistic)
phi2 <- max(0, chi2 / n - (r - 1) * (k - 1) / (n - 1))
den <- min(r - (r - 1)^2 / (n - 1) - 1, k - (k - 1)^2 / (n - 1) - 1)
if (den > 0) sqrt(phi2 / den) else NA_real_
}
eta <- function(y, g) {
# correlation ratio: sqrt(SS_between / SS_total)
if (length(y) < 3 || length(unique(g)) < 2) return(NA_real_)
m <- mean(y)
ssb <- sum(tapply(y, g, function(s) length(s) * (mean(s) - m)^2))
sst <- sum((y - m)^2)
if (sst > 0) sqrt(ssb / sst) else NA_real_
}
association <- function(a, b, a_num, b_num, method) {
ok <- !is.na(a) & !is.na(b) # pairwise-complete rows
a <- a[ok]; b <- b[ok]
if (a_num && b_num) return(if (length(a) > 2) abs(stats::cor(a, b, method = method)) else NA_real_)
if (a_num) return(eta(a, as.character(b)))
if (b_num) return(eta(b, as.character(a)))
cramers_v(as.character(a), as.character(b))
}
vars <- c("income_k", "monthly_spend", "tenure_months", "age", "segment", "plan", "region", "churned")
is_num <- vars %in% c("income_k", "monthly_spend", "tenure_months", "age") # booleans count as categorical
m <- matrix(1, length(vars), length(vars), dimnames = list(vars, vars))
for (i in seq_along(vars)) for (j in seq_along(vars)) if (i != j)
m[i, j] <- association(df[[vars[i]]], df[[vars[j]]], is_num[i], is_num[j], "pearson")
ord <- vars
cells <- expand.grid(row = ord, col = ord, stringsAsFactors = FALSE)
cells$v <- m[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 = v)) +
geom_tile(colour = "white", linewidth = 0.5) +
geom_text(aes(label = sprintf("%.2f", v)), size = 3) +
scale_fill_gradient(low = seq_ramp[1], high = seq_ramp[2], limits = c(0, 1), name = "|r|, V or η") +
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 assoc-matrix-demo.csv · app theme from the optional codesplashr 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.