svgtreemap
Treemap
How is a total split across a hierarchy of categories?
How to read it
- Read rectangle area as value.
- Read colour as the top-level group.
- Compare large blocks; use labels for the small ones.
- Callout 1: A big rectangle: a large share of the total.
- Callout 2: Heading: the top-level group and its share.
Watch out
- People compare areas poorly. Use a sorted bar chart when exact differences matter.
Defaults
- Children per node
- 10
- How many sub-levels to show under each parent; the rest are grouped.
- Range 3 to 20, step 1
Pinned in the code
- Area ∝ sum of the size column (row count when none); node order by value.
- Layout: squarified tiling (Bruls, Huizing & van Wijk 2000) with d3-hierarchy's golden-ratio target aspect.
- Beyond the per-node limit, the smallest children are pooled into “Other” (grey).
- Labels are drawn only where they fit; tooltips carry the full path, value and share of total.
# Treemap — Codesplash Chart Lab (recipe "treemap")
# controls: maxChildren=10
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
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("treemap-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
def tree_nodes(frame, levels, size=None, max_children=10):
"""Hierarchy nodes like the app: value = sum of size (rows counted when none, non-positive rows skipped);
children sorted by value (ties alphabetical); beyond max_children the smallest pool into "Other";
missing labels become "(missing)". Returns depth-first rows: id, label, parent, value, depth, top."""
w = pd.to_numeric(frame[size], errors="coerce") if size else pd.Series(1.0, index=frame.index)
w = w.where(np.isfinite(w), 0).fillna(0)
keep = w > 0
sub = frame.loc[keep, levels].astype(object)
paths = sub.where(sub.notna(), "(missing)").astype(str)
w = w[keep]
nodes = []
def walk(index, depth, parent, top):
if depth == len(levels):
return
key = paths.loc[index, levels[depth]]
sums = w.loc[index].groupby(key).sum()
kids = sorted(sums.items(), key=lambda kv: (-kv[1], kv[0]))
shown = kids[: max_children - 1] if len(kids) > max_children else kids
entries = [(name, value, False) for name, value in shown]
if len(kids) > len(shown):
entries.append(("Other", sum(v for _, v in kids[len(shown):]), True))
entries.sort(key=lambda e: (-e[1], e[2])) # d3 re-sorts siblings by value; "Other" last among ties
for name, value, pooled in entries:
nid = f"{parent} › {name}"
nodes.append({"id": nid, "label": name, "parent": parent, "value": value, "depth": depth + 1, "top": top or name})
if not pooled:
walk(index[(key == name).to_numpy()], depth + 1, nid, top or name)
walk(paths.index, 0, "All", None)
return pd.DataFrame(nodes)
PHI = (1 + 5 ** 0.5) / 2
def squarify(values, x0, y0, x1, y1, ratio=PHI):
"""d3.treemapSquarify: rows grow while their worst aspect ratio improves (Bruls et al. 2000)."""
out, i0, n, value = [], 0, len(values), float(sum(values))
while i0 < n:
dx, dy = max(x1 - x0, 1e-9), max(y1 - y0, 1e-9)
s = lo = hi = values[i0]
i1 = i0 + 1
alpha = max(dy / dx, dx / dy) / (value * ratio)
best = max(hi / (s * s * alpha), s * s * alpha / lo)
while i1 < n:
v = values[i1]
beta = (s + v) ** 2 * alpha
r = max(max(hi, v) / beta, beta / min(lo, v))
if r > best:
break
s, lo, hi, best, i1 = s + v, min(lo, v), max(hi, v), r, i1 + 1
if dx < dy: # a strip across the top, nodes side by side
yb, x = y0 + dy * s / value, x0
for v in values[i0:i1]:
out.append((x, y0, x + dx * v / s, yb))
x += dx * v / s
y0 = yb
else: # a strip down the left, nodes stacked
xb, y = x0 + dx * s / value, y0
for v in values[i0:i1]:
out.append((x0, y, xb, y + dy * v / s))
y += dy * v / s
x0 = xb
value -= s
i0 = i1
return out
def layout_treemap(nodes, W=960, H=540, pad=2, header=17):
"""Nested squarified rectangles in a W × H canvas (y down), with the app's 2 px padding and a
17 px header strip on top-level groups."""
parents = set(nodes["parent"])
rects = {}
def place(parent, x0, y0, x1, y1):
kids = nodes[nodes["parent"] == parent]
for nd, (a, b, c, d) in zip(kids.itertuples(), squarify(kids["value"].tolist(), x0, y0, x1, y1)):
a, b, c, d = a + pad / 2, b + pad / 2, c - pad / 2, d - pad / 2
rects[nd.id] = (a, b, c, d)
if nd.id in parents:
top = header if nd.depth == 1 and c - a > 40 else pad
place(nd.id, a + pad, b + top, c - pad, d - pad)
place("All", 0, 0, W, H)
return nodes.assign(**{k: [rects[i][j] for i in nodes["id"]] for j, k in enumerate(["x0", "y0", "x1", "y1"])})
OTHER = "#9aa0a6" # pooled levels
nodes = tree_nodes(df, ["category", "subcategory"], "revenue", max_children=10)
rects = layout_treemap(nodes)
tops = list(nodes.loc[nodes["depth"] == 1, "label"])
top_color = {t: (OTHER if t == "Other" else PALETTE[i % len(PALETTE)]) for i, t in enumerate(tops)}
ALPHA = {1: 1.0, 2: 0.72, 3: 0.5, 4: 0.36}
parents = set(nodes["parent"])
total = nodes.loc[nodes["depth"] == 1, "value"].sum()
from matplotlib.patches import Rectangle
fig, ax = plt.subplots(figsize=(9.6, 5.4))
for nd in rects.itertuples():
w, h = nd.x1 - nd.x0, nd.y1 - nd.y0
leaf = nd.id not in parents
color = top_color[nd.top]
ax.add_patch(Rectangle((nd.x0, nd.y0), w, h, facecolor=color, alpha=0.88 if leaf else 0.18, edgecolor="none"))
if leaf and w > 60 and h > 22: # labels only where they fit
ax.text(nd.x0 + 4, nd.y0 + 4, f"{nd.label}\n{nd.value / total:.1%}", ha="left", va="top", fontsize=7, color="white")
elif not leaf and nd.depth == 1 and w > 40:
ax.text(nd.x0 + 4, nd.y0 + 3, nd.label, ha="left", va="top", fontsize=8, fontweight="bold")
ax.set_xlim(0, 960)
ax.set_ylim(540, 0) # y down, like the SVG
ax.axis("off")
plt.show()Needs pandas, numpy, matplotlib · reads treemap-demo.csv · app theme from the optional codesplash helper
# Treemap — Codesplash Chart Lab (recipe "treemap")
# controls: maxChildren=10
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("treemap-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
def tree_nodes(frame, levels, size=None, max_children=10):
"""Hierarchy nodes like the app: value = sum of size (rows counted when none, non-positive rows skipped);
children sorted by value (ties alphabetical); beyond max_children the smallest pool into "Other";
missing labels become "(missing)". Returns depth-first rows: id, label, parent, value, depth, top."""
w = pd.to_numeric(frame[size], errors="coerce") if size else pd.Series(1.0, index=frame.index)
w = w.where(np.isfinite(w), 0).fillna(0)
keep = w > 0
sub = frame.loc[keep, levels].astype(object)
paths = sub.where(sub.notna(), "(missing)").astype(str)
w = w[keep]
nodes = []
def walk(index, depth, parent, top):
if depth == len(levels):
return
key = paths.loc[index, levels[depth]]
sums = w.loc[index].groupby(key).sum()
kids = sorted(sums.items(), key=lambda kv: (-kv[1], kv[0]))
shown = kids[: max_children - 1] if len(kids) > max_children else kids
entries = [(name, value, False) for name, value in shown]
if len(kids) > len(shown):
entries.append(("Other", sum(v for _, v in kids[len(shown):]), True))
entries.sort(key=lambda e: (-e[1], e[2])) # d3 re-sorts siblings by value; "Other" last among ties
for name, value, pooled in entries:
nid = f"{parent} › {name}"
nodes.append({"id": nid, "label": name, "parent": parent, "value": value, "depth": depth + 1, "top": top or name})
if not pooled:
walk(index[(key == name).to_numpy()], depth + 1, nid, top or name)
walk(paths.index, 0, "All", None)
return pd.DataFrame(nodes)
nodes = tree_nodes(df, ["category", "subcategory"], "revenue", max_children=10)
PHI = (1 + 5 ** 0.5) / 2 # d3's golden-ratio squarify target
OTHER = "#9aa0a6" # pooled levels
tops = list(nodes.loc[nodes["depth"] == 1, "label"])
top_color = {t: (OTHER if t == "Other" else PALETTE[i % len(PALETTE)]) for i, t in enumerate(tops)}
ALPHA = {1: 1.0, 2: 0.72, 3: 0.5, 4: 0.36}
fig = go.Figure(go.Treemap(
ids=nodes["id"], labels=nodes["label"], parents=["" if p == "All" else p for p in nodes["parent"]],
values=nodes["value"], branchvalues="total", sort=True,
marker=dict(colors=[top_color[t] for t in nodes["top"]]),
tiling=dict(packing="squarify", squarifyratio=PHI, pad=2),
hovertemplate="%{id}<br>%{value:,.4g} (%{percentRoot:.1%} of total)<extra></extra>",
))
fig.update_layout(margin=dict(t=30, l=10, r=10, b=10))
fig.show()Needs pandas, numpy, plotly · reads treemap-demo.csv · app theme from the optional codesplash helper
# Treemap — Codesplash Chart Lab (recipe "treemap")
# controls: maxChildren=10
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("treemap-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["category"]] <- factor(df[["category"]])
df[["subcategory"]] <- factor(df[["subcategory"]])
update_geom_defaults("text", list(colour = "#131922")) # labels in the theme's text colour
tree_nodes <- function(frame, levels, size = NULL, max_children = 10) {
# hierarchy nodes like the app: value = sum of size (rows counted when none, non-positive rows skipped);
# children sorted by value (ties alphabetical); beyond max_children the smallest pool into "Other";
# missing labels become "(missing)". Returns depth-first rows: id, label, parent, value, depth, top.
w <- if (is.null(size)) rep(1, nrow(frame)) else suppressWarnings(as.numeric(frame[[size]]))
w[!is.finite(w)] <- 0
keep <- w > 0
paths <- lapply(levels, function(l) {
v <- as.character(frame[[l]])[keep]
ifelse(is.na(v), "(missing)", v)
})
w <- w[keep]
out <- list()
walk <- function(idx, depth, parent, top) {
if (depth > length(levels)) return(invisible(NULL))
key <- paths[[depth]][idx]
sums <- tapply(w[idx], key, sum)
o <- order(-sums, names(sums))
kids <- names(sums)[o]
vals <- as.numeric(sums)[o]
m <- if (length(kids) > max_children) max_children - 1 else length(kids)
e <- data.frame(label = kids[seq_len(m)], value = vals[seq_len(m)], pooled = FALSE)
if (length(kids) > m) e <- rbind(e, data.frame(label = "Other", value = sum(vals[-seq_len(m)]), pooled = TRUE))
e <- e[order(-e$value, e$pooled), ] # d3 re-sorts siblings by value; "Other" last among ties
for (k in seq_len(nrow(e))) {
id <- paste(parent, e$label[k], sep = " \u203a ")
tp <- if (is.null(top)) e$label[k] else top
out[[length(out) + 1]] <<- data.frame(id = id, label = e$label[k], parent = parent, value = e$value[k], depth = depth, top = tp)
if (!e$pooled[k]) walk(idx[key == e$label[k]], depth + 1, id, tp)
}
}
walk(seq_along(w), 1, "All", NULL)
do.call(rbind, out)
}
squarify <- function(values, x0, y0, x1, y1, ratio = (1 + sqrt(5)) / 2) {
# d3.treemapSquarify: rows grow while their worst aspect ratio improves (Bruls et al. 2000)
out <- matrix(NA_real_, length(values), 4)
i0 <- 1
n <- length(values)
value <- sum(values)
while (i0 <= n) {
dx <- max(x1 - x0, 1e-9)
dy <- max(y1 - y0, 1e-9)
s <- lo <- hi <- values[i0]
i1 <- i0 + 1
alpha <- max(dy / dx, dx / dy) / (value * ratio)
best <- max(hi / (s * s * alpha), s * s * alpha / lo)
while (i1 <= n) {
v <- values[i1]
beta <- (s + v)^2 * alpha
r <- max(max(hi, v) / beta, beta / min(lo, v))
if (r > best) break
s <- s + v; lo <- min(lo, v); hi <- max(hi, v); best <- r; i1 <- i1 + 1
}
rows <- i0:(i1 - 1)
if (dx < dy) { # a strip across the top, nodes side by side
yb <- y0 + dy * s / value
xs <- x0 + dx * cumsum(c(0, values[rows])) / s
out[rows, ] <- cbind(head(xs, -1), y0, tail(xs, -1), yb)
y0 <- yb
} else { # a strip down the left, nodes stacked
xb <- x0 + dx * s / value
ys <- y0 + dy * cumsum(c(0, values[rows])) / s
out[rows, ] <- cbind(x0, head(ys, -1), xb, tail(ys, -1))
x0 <- xb
}
value <- value - s
i0 <- i1
}
out
}
layout_treemap <- function(nodes, W = 960, H = 540, pad = 2, header = 17) {
# nested squarified rectangles in a W × H canvas (y down), 2 px padding, 17 px header on top-level groups
nodes$x0 <- nodes$y0 <- nodes$x1 <- nodes$y1 <- NA_real_
parents <- unique(nodes$parent)
place <- function(parent, x0, y0, x1, y1) {
k <- which(nodes$parent == parent)
if (!length(k)) return(invisible(NULL))
r <- squarify(nodes$value[k], x0, y0, x1, y1)
for (j in seq_along(k)) {
b <- r[j, ] + c(pad, pad, -pad, -pad) / 2
nodes[k[j], c("x0", "y0", "x1", "y1")] <<- as.list(b)
if (nodes$id[k[j]] %in% parents) {
top <- if (nodes$depth[k[j]] == 1 && b[3] - b[1] > 40) header else pad
place(nodes$id[k[j]], b[1] + pad, b[2] + top, b[3] - pad, b[4] - pad)
}
}
}
place("All", 0, 0, W, H)
nodes
}
nodes <- tree_nodes(df, c("category", "subcategory"), "revenue", max_children = 10)
nodes <- layout_treemap(nodes)
tops <- nodes$label[nodes$depth == 1]
top_color <- setNames(rep(cs_cat, length.out = length(tops)), tops)
top_color[tops == "Other"] <- "#9aa0a6"
nodes$fill <- top_color[nodes$top]
nodes$alpha <- c(1, 0.72, 0.5, 0.36)[pmin(nodes$depth, 4)] # lighter for deeper levels
nodes$leaf <- !(nodes$id %in% nodes$parent)
total <- sum(nodes$value[nodes$depth == 1])
leaves <- nodes[nodes$leaf, ]
groups <- nodes[!nodes$leaf & nodes$depth == 1, ]
p <- ggplot() +
geom_rect(data = groups, aes(xmin = x0, xmax = x1, ymin = y0, ymax = y1, fill = fill), alpha = 0.18) +
geom_rect(data = leaves, aes(xmin = x0, xmax = x1, ymin = y0, ymax = y1, fill = fill), alpha = 0.88) +
geom_text(data = groups[groups$x1 - groups$x0 > 40, ], aes(x = x0 + 4, y = y0 + 3, label = label), hjust = 0, vjust = 1, size = 2.8, fontface = "bold") +
geom_text(data = leaves[leaves$x1 - leaves$x0 > 60 & leaves$y1 - leaves$y0 > 22, ],
aes(x = x0 + 4, y = y0 + 4, label = sprintf("%s\n%.1f%%", label, 100 * value / total)), hjust = 0, vjust = 1, size = 2.3, colour = "white", lineheight = 0.9) +
scale_fill_identity() +
scale_y_reverse() + # y down, like the SVG
coord_fixed() +
theme_cs +
theme(axis.text = element_blank(), axis.title = element_blank(), axis.ticks = element_blank(), axis.line = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank())
print(p)Needs ggplot2 · reads treemap-demo.csv · app theme from the optional codesplashr helper
-- Treemap — Codesplash Chart Lab (recipe "treemap")
-- controls: maxChildren=10
-- node totals for every prefix of the hierarchy (ROLLUP) and each node's rank among its siblings;
-- the app pools siblings with rank ≥ 10 into "Other" when a parent has more than 10 children
WITH d AS (SELECT coalesce("category"::VARCHAR, '(missing)') AS "category", coalesce("subcategory"::VARCHAR, '(missing)') AS "subcategory", CASE WHEN isfinite("revenue") THEN "revenue" ELSE 0 END AS w FROM read_csv('treemap-demo.csv')),
nodes AS (
SELECT "category", "subcategory", (1 - grouping("category")) + (1 - grouping("subcategory")) AS depth, sum(w) AS value
FROM d
WHERE w > 0
GROUP BY ROLLUP ("category", "subcategory")
)
SELECT *, row_number() OVER (
PARTITION BY depth, CASE WHEN depth > 1 THEN "category" END
ORDER BY value DESC, "category", "subcategory"
) AS sibling_rank -- rank among siblings (same parent path), ties alphabetical
FROM nodes
ORDER BY depth, "category", "subcategory";Needs duckdb · reads treemap-demo.csv
- Layout: the d3 squarify algorithm (golden-ratio target) re-implemented inline in Python and R; padding approximates the app's.