svgmatrix-heatmap
Matrix heatmap
What do the values of a square or rectangular result matrix look like at a glance?
How to read it
- Read a cell's colour and its printed value together.
- Check the colour bar: diverging around zero or sequential.
- Look for blocks and for cells that break the pattern.
- Callout 1: A dark cell: a large value.
- Callout 2: The other hue: negative values.
- 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
# Matrix heatmap — Codesplash Chart Lab (recipe "matrix-heatmap")
# controls: scale=diverging
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("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
d = df.dropna(subset=[ROW, COL])
rows, cols = levels_of(d[ROW]), levels_of(d[COL])
piv = lambda value: d.assign(_r=d[ROW].astype(str), _c=d[COL].astype(str)).pivot_table(index="_r", columns="_c", values=value, aggfunc="first").reindex(index=rows, columns=cols)
m = piv(V)
text = piv(LAB).astype(str).to_numpy() if LAB else np.vectorize(lambda v: "" if np.isnan(v) else f"{v:.2f}")(m.to_numpy(float))
scale = [[0, DIV[0]], [0.5, DIV[len(DIV) // 2]], [1, DIV[-1]]] if DIVERGING else [[0, SEQ[0]], [1, SEQ[-1]]]
lim = float(np.nanmax(np.abs(m.to_numpy(float)))) or 1
fig = go.Figure(go.Heatmap(z=m.to_numpy(float), x=cols, y=rows, colorscale=scale, zmid=0 if DIVERGING else None,
zmin=-lim if DIVERGING else None, zmax=lim if DIVERGING else None, text=text, texttemplate="%{text}", colorbar=dict(title=V)))
fig.update_yaxes(autorange="reversed")
fig.show()Needs pandas, numpy, plotly · reads matrix-heatmap-demo.csv · app theme from the optional codesplash helper
# Matrix heatmap — Codesplash Chart Lab (recipe "matrix-heatmap")
# controls: scale=diverging
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("matrix-heatmap-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["variable"]] <- factor(df[["variable"]], levels = c("age", "BMI", "systolic BP", "cholesterol", "glucose", "activity"))
df[["with"]] <- factor(df[["with"]], levels = c("age", "BMI", "systolic BP", "cholesterol", "glucose", "activity"))
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
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
row_col <- "variable"
col_col <- "with"
v_col <- "r"
lab_col <- NULL
diverging <- TRUE
d <- df[!is.na(df[[row_col]]) & !is.na(df[[col_col]]), ]
d <- data.frame(r = factor(as.character(d[[row_col]]), levels = rev(levels_of(d[[row_col]]))),
k = factor(as.character(d[[col_col]]), levels = levels_of(d[[col_col]])), v = d[[v_col]],
lab = if (is.null(lab_col)) ifelse(is.na(d[[v_col]]), "", sprintf("%.2f", d[[v_col]])) else as.character(d[[lab_col]]))
lim <- max(abs(d$v), na.rm = TRUE)
p <- ggplot(d, aes(k, r, fill = v)) + geom_tile(colour = "white") + geom_text(aes(label = lab), size = 3) +
{ if (diverging) scale_fill_gradient2(low = div_ramp[1], mid = div_ramp[ceiling(length(div_ramp) / 2)], high = div_ramp[length(div_ramp)], midpoint = 0, limits = c(-lim, lim))
else scale_fill_gradient(low = seq_ramp[1], high = seq_ramp[length(seq_ramp)]) } +
labs(x = NULL, y = NULL, fill = v_col) + theme_cs + theme(axis.text.x = element_text(angle = 45, hjust = 1))
print(p)Needs ggplot2 · reads matrix-heatmap-demo.csv · app theme from the optional codesplashr helper