Skip to content
svgmatrix-heatmap

Matrix heatmap

What do the values of a square or rectangular result matrix look like at a glance?

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

How to read it

  1. Read a cell's colour and its printed value together.
  2. Check the colour bar: diverging around zero or sequential.
  3. Look for blocks and for cells that break the pattern.
  1. Callout 1: A dark cell: a large value.
  2. Callout 2: The other hue: negative values.
  3. Callout 3: Colour bar: the scale.

Watch out

  • Values in a matrix aren't independent, so one cell standing out may be noise.

Defaults

Colour scale
Diverging (centred on 0)
Linear shows the dense cells; log or square root reveals the sparse ones too.
Also: Sequential

Pinned in the code

  • Draws the engine's numbers as given (precomputed by the Python or R analysis); the chart computes nothing statistical.
  • Diverging scales are symmetric around 0 (correlations, standardized residuals); sequential scales run min → max (counts, p-values).
  • Engine-supplied controls min/max fix the colour range (e.g. −1 to 1 for correlations); cell text uses the label column when given (e.g. ".42*").
  • Row and column order follow the stored level order (the engine may cluster them).
# Matrix heatmap — Codesplash Chart Lab (recipe "matrix-heatmap")
# controls: scale=diverging
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
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("matrix-heatmap-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["variable"] = pd.Categorical(df["variable"].astype("string"), categories=["age", "BMI", "systolic BP", "cholesterol", "glucose", "activity"])
df["with"] = pd.Categorical(df["with"].astype("string"), categories=["age", "BMI", "systolic BP", "cholesterol", "glucose", "activity"])

_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 levels_of(s):
    """Declared level order (categoricals), else order of first appearance."""
    if isinstance(s.dtype, pd.CategoricalDtype):
        return [v for v in s.cat.categories if (s == v).any()]
    return list(dict.fromkeys(s.dropna().astype(str)))
ROW = "variable"
COL = "with"
V = "r"
LAB = None
DIVERGING = True  # diverging around 0 (correlations) or sequential
d = df.dropna(subset=[ROW, COL])
rows, cols = levels_of(d[ROW]), levels_of(d[COL])
m = d.assign(_r=d[ROW].astype(str), _c=d[COL].astype(str)).pivot_table(index="_r", columns="_c", values=V, aggfunc="first").reindex(index=rows, columns=cols)
vals = m.to_numpy(float)
if DIVERGING:
    lim = np.nanmax(np.abs(vals)) or 1
    cmap, vmin, vmax = LinearSegmentedColormap.from_list("div", [DIV[0], DIV[len(DIV) // 2], DIV[-1]]), -lim, lim
else:
    cmap, vmin, vmax = LinearSegmentedColormap.from_list("seq", [SEQ[0], SEQ[-1]]), np.nanmin(vals), np.nanmax(vals)
labels = None
if LAB:
    labels = d.assign(_r=d[ROW].astype(str), _c=d[COL].astype(str)).pivot_table(index="_r", columns="_c", values=LAB, aggfunc="first").reindex(index=rows, columns=cols)
fig, ax = plt.subplots(figsize=(7, 6))
im = ax.imshow(vals, cmap=cmap, vmin=vmin, vmax=vmax, aspect="auto")
for i in range(len(rows)):
    for j in range(len(cols)):
        v = vals[i, j]
        if np.isnan(v):
            continue
        txt = str(labels.iloc[i, j]) if labels is not None else f"{v:.2f}"
        light = abs((v - vmin) / ((vmax - vmin) or 1) - (0.5 if DIVERGING else 0)) > (0.3 if DIVERGING else 0.6)
        ax.text(j, i, txt, ha="center", va="center", fontsize=8, color="white" if light else "black")
ax.set_xticks(range(len(cols)), cols, rotation=45, ha="right")
ax.set_yticks(range(len(rows)), rows)
fig.colorbar(im, ax=ax, label=V)
plt.show()

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