svgcorr-heatmap
Correlation heatmap
Which numeric variables move together, and how strongly?
How to read it
- Find the darkest cells off the diagonal: the strongest correlations.
- Check colour for sign: one hue for positive, the other for negative.
- Use clustered order to see blocks of variables that move together.
- Callout 1: A dark off-diagonal cell: a strong correlation.
- Callout 2: The other hue: a negative correlation.
- Callout 3: Colour bar: the scale from −1 to 1.
Watch out
- Pearson's r measures straight-line association only, so a U-shape can give r near zero.
- Scanning many cells finds large values by chance. Adjust for multiplicity before claiming one.
Defaults
- Coefficient
- Pearson r
- Pearson measures straight-line association; Spearman measures any steadily rising or falling trend.
- Also: Spearman ρ
- Cluster order
- On
- 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
- Pearson r or Spearman ρ (Pearson on average ranks) over pairwise-complete rows; n per pair is in each cell's tooltip.
- Diverging ramp centred at 0 (negative → warm, positive → cool), saturating at ±1.
- Cluster order: average-linkage hierarchical clustering on 1 − |r| (R `hclust(as.dist(1 - abs(r)), "average")` leaf grouping), so related variables sit together.
- Values are printed APA-style without the leading zero (.42, −.08).
# Correlation heatmap — Codesplash Chart Lab (recipe "corr-heatmap")
# controls: method=pearson, cluster=true, triangle=full, values=true
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("corr-heatmap-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
_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")
VARS = ["income_k", "monthly_spend", "tenure_months", "site_visits", "churn_risk", "support_tickets", "age"]
r = df[VARS].corr(method="pearson", min_periods=3) # pairwise-complete rows
order = cluster_order(r.to_numpy())
r = r.iloc[order, order]
mask = None
fig, ax = plt.subplots(figsize=(1 + 0.6 * len(VARS), 0.8 + 0.5 * len(VARS)))
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": "Pearson r", "shrink": 0.7})
ax.grid(False)
plt.show()Needs pandas, numpy, matplotlib, seaborn · reads corr-heatmap-demo.csv · app theme from the optional codesplash helper
# Correlation heatmap — Codesplash Chart Lab (recipe "corr-heatmap")
# controls: method=pearson, cluster=true, triangle=full, values=true
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("corr-heatmap-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
_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")
VARS = ["income_k", "monthly_spend", "tenure_months", "site_visits", "churn_risk", "support_tickets", "age"]
r = df[VARS].corr(method="pearson", min_periods=3)
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}", hovertemplate="%{y} × %{x}: %{z:.3f}<extra></extra>"))
fig.update_layout(yaxis_autorange="reversed", width=120 + 50 * len(VARS), height=100 + 45 * len(VARS))
fig.show()Needs pandas, numpy, plotly · reads corr-heatmap-demo.csv · app theme from the optional codesplash helper
# Correlation heatmap — Codesplash Chart Lab (recipe "corr-heatmap")
# controls: method=pearson, cluster=true, 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("corr-heatmap-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
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))))
vars <- c("income_k", "monthly_spend", "tenure_months", "site_visits", "churn_risk", "support_tickets", "age")
r <- stats::cor(df[vars], use = "pairwise.complete.obs", method = "pearson") # ranks per pair for Spearman
ord <- vars[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 = "Pearson 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 corr-heatmap-demo.csv · app theme from the optional codesplashr helper
-- Correlation heatmap — Codesplash Chart Lab (recipe "corr-heatmap")
-- controls: method=pearson, cluster=true, triangle=full, values=true
-- Pearson r for every pair over pairwise-complete rows
SELECT 'income_k' AS a, 'monthly_spend' AS b, corr("income_k", "monthly_spend") AS r, regr_count("income_k", "monthly_spend") AS n FROM read_csv('corr-heatmap-demo.csv')
UNION ALL
SELECT 'income_k' AS a, 'tenure_months' AS b, corr("income_k", "tenure_months") AS r, regr_count("income_k", "tenure_months") AS n FROM read_csv('corr-heatmap-demo.csv')
UNION ALL
SELECT 'income_k' AS a, 'site_visits' AS b, corr("income_k", "site_visits") AS r, regr_count("income_k", "site_visits") AS n FROM read_csv('corr-heatmap-demo.csv')
UNION ALL
SELECT 'income_k' AS a, 'churn_risk' AS b, corr("income_k", "churn_risk") AS r, regr_count("income_k", "churn_risk") AS n FROM read_csv('corr-heatmap-demo.csv')
UNION ALL
SELECT 'income_k' AS a, 'support_tickets' AS b, corr("income_k", "support_tickets") AS r, regr_count("income_k", "support_tickets") AS n FROM read_csv('corr-heatmap-demo.csv')
UNION ALL
SELECT 'income_k' AS a, 'age' AS b, corr("income_k", "age") AS r, regr_count("income_k", "age") AS n FROM read_csv('corr-heatmap-demo.csv')
UNION ALL
SELECT 'monthly_spend' AS a, 'tenure_months' AS b, corr("monthly_spend", "tenure_months") AS r, regr_count("monthly_spend", "tenure_months") AS n FROM read_csv('corr-heatmap-demo.csv')
UNION ALL
SELECT 'monthly_spend' AS a, 'site_visits' AS b, corr("monthly_spend", "site_visits") AS r, regr_count("monthly_spend", "site_visits") AS n FROM read_csv('corr-heatmap-demo.csv')
UNION ALL
SELECT 'monthly_spend' AS a, 'churn_risk' AS b, corr("monthly_spend", "churn_risk") AS r, regr_count("monthly_spend", "churn_risk") AS n FROM read_csv('corr-heatmap-demo.csv')
UNION ALL
SELECT 'monthly_spend' AS a, 'support_tickets' AS b, corr("monthly_spend", "support_tickets") AS r, regr_count("monthly_spend", "support_tickets") AS n FROM read_csv('corr-heatmap-demo.csv')
UNION ALL
SELECT 'monthly_spend' AS a, 'age' AS b, corr("monthly_spend", "age") AS r, regr_count("monthly_spend", "age") AS n FROM read_csv('corr-heatmap-demo.csv')
UNION ALL
SELECT 'tenure_months' AS a, 'site_visits' AS b, corr("tenure_months", "site_visits") AS r, regr_count("tenure_months", "site_visits") AS n FROM read_csv('corr-heatmap-demo.csv')
UNION ALL
SELECT 'tenure_months' AS a, 'churn_risk' AS b, corr("tenure_months", "churn_risk") AS r, regr_count("tenure_months", "churn_risk") AS n FROM read_csv('corr-heatmap-demo.csv')
UNION ALL
SELECT 'tenure_months' AS a, 'support_tickets' AS b, corr("tenure_months", "support_tickets") AS r, regr_count("tenure_months", "support_tickets") AS n FROM read_csv('corr-heatmap-demo.csv')
UNION ALL
SELECT 'tenure_months' AS a, 'age' AS b, corr("tenure_months", "age") AS r, regr_count("tenure_months", "age") AS n FROM read_csv('corr-heatmap-demo.csv')
UNION ALL
SELECT 'site_visits' AS a, 'churn_risk' AS b, corr("site_visits", "churn_risk") AS r, regr_count("site_visits", "churn_risk") AS n FROM read_csv('corr-heatmap-demo.csv')
UNION ALL
SELECT 'site_visits' AS a, 'support_tickets' AS b, corr("site_visits", "support_tickets") AS r, regr_count("site_visits", "support_tickets") AS n FROM read_csv('corr-heatmap-demo.csv')
UNION ALL
SELECT 'site_visits' AS a, 'age' AS b, corr("site_visits", "age") AS r, regr_count("site_visits", "age") AS n FROM read_csv('corr-heatmap-demo.csv')
UNION ALL
SELECT 'churn_risk' AS a, 'support_tickets' AS b, corr("churn_risk", "support_tickets") AS r, regr_count("churn_risk", "support_tickets") AS n FROM read_csv('corr-heatmap-demo.csv')
UNION ALL
SELECT 'churn_risk' AS a, 'age' AS b, corr("churn_risk", "age") AS r, regr_count("churn_risk", "age") AS n FROM read_csv('corr-heatmap-demo.csv')
UNION ALL
SELECT 'support_tickets' AS a, 'age' AS b, corr("support_tickets", "age") AS r, regr_count("support_tickets", "age") AS n FROM read_csv('corr-heatmap-demo.csv');Needs duckdb · reads corr-heatmap-demo.csv