Skip to content
svgtreemap

Treemap

How is a total split across a hierarchy of categories?

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

How to read it

  1. Read rectangle area as value.
  2. Read colour as the top-level group.
  3. Compare large blocks; use labels for the small ones.
  1. Callout 1: A big rectangle: a large share of the total.
  2. 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

  • Layout: the d3 squarify algorithm (golden-ratio target) re-implemented inline in Python and R; padding approximates the app's.