Skip to content
svgcorr-heatmap

Correlation heatmap

Which numeric variables move together, and how strongly?

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

How to read it

  1. Find the darkest cells off the diagonal: the strongest correlations.
  2. Check colour for sign: one hue for positive, the other for negative.
  3. Use clustered order to see blocks of variables that move together.
  1. Callout 1: A dark off-diagonal cell: a strong correlation.
  2. Callout 2: The other hue: a negative correlation.
  3. 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