Skip to content
ChartslibraryUI Get Pro

Treemap

Many parts of one whole, sized by area and optionally grouped.

FreeMIT · install in one command<Treemap />

When to use

  • Spend by vendor grouped by category
  • Spotting the few items that dominate a total

When not to use

Good practice

  • Group one level at most.
  • Use the table view for the long tail of tiny tiles.

Installation

Treemap is free under the MIT license.

$ npx shadcn@latest add https://chartslibraryui.com/r/treemap.json

Installs the chart, its dependencies and the shared core into your components folder.

Then import the theme once: import "@/components/charts/core/charts.css" Installation guide

Usage

import { Treemap } from "@/components/charts/treemap";
import { spendTreemap } from "./sample-data";

export function Example() {
  return (
    <Treemap
      title="Infrastructure is 40% of software spend"
      subtitle="Annual software spend by vendor, USD"
      data={spendTreemap}
      label="name"
      value="value"
      group="group"
      format="currency"
    />
  );
}

Data

Rows with a label key, a positive value key and an optional group key.

[{ name: "Cloud hosting", group: "Infrastructure", value: 96000 }, ...]

Missing values are null. Invalid values make the chart say what’s wrong instead of drawing a misleading picture. How charts handle bad data

Props

Every chart also accepts the shared frame props: title, subtitle, source, height, mode, toolbar. Common API

export interface TreemapProps extends FrameProps {
  data: Row[];
  /** Key of the item name. */
  label: string;
  /** Key of the item size. Must be positive. */
  value: string;
  /** Optional key that groups items one level (each group gets a colour). */
  group?: string;
  format?: FormatInput;
}

Source

Installs treemap.tsx and the shared core/ (11 files).

View treemap.tsx
"use client";

import { useMemo } from "react";
import { color as tokens } from "./core/color";
import { readNum, type Issue, type Row } from "./core/data";
import { formatShare, formatValue, labelFormatter, type FormatInput } from "./core/format";
import { ChartFrame, ChartTooltip, useActiveIndex, type FrameProps } from "./core/frame";
import { roundedRect } from "./core/path";
import { textWidth, truncate } from "./core/text";

export interface TreemapProps extends FrameProps {
  data: Row[];
  /** Key of the item name. */
  label: string;
  /** Key of the item size. Must be positive. */
  value: string;
  /** Optional key that groups items one level (each group gets a colour). */
  group?: string;
  format?: FormatInput;
}

interface Rect {
  x: number;
  y: number;
  w: number;
  h: number;
}

interface Node {
  name: string;
  value: number;
  group?: string;
}

/** Squarified treemap layout (Bruls, Huizing, van Wijk). Returns rects in input order. */
export function squarify(values: number[], box: Rect): Rect[] {
  const out: Rect[] = new Array(values.length);
  const order = values.map((v, i) => ({ v, i })).filter((d) => d.v > 0).sort((a, b) => b.v - a.v);
  const total = order.reduce((a, d) => a + d.v, 0);
  if (!total) return values.map(() => ({ x: box.x, y: box.y, w: 0, h: 0 }));
  const scale = (box.w * box.h) / total;
  let rect = { ...box };
  let row: { v: number; i: number }[] = [];
  const worst = (r: { v: number }[], side: number) => {
    const s = r.reduce((a, d) => a + d.v * scale, 0);
    const max = Math.max(...r.map((d) => d.v * scale));
    const min = Math.min(...r.map((d) => d.v * scale));
    return Math.max((side * side * max) / (s * s), (s * s) / (side * side * min));
  };
  const layoutRow = (r: { v: number; i: number }[]) => {
    const s = r.reduce((a, d) => a + d.v * scale, 0);
    if (rect.w >= rect.h) {
      const w = s / rect.h;
      let y = rect.y;
      for (const d of r) {
        const h = (d.v * scale) / w;
        out[d.i] = { x: rect.x, y, w, h };
        y += h;
      }
      rect = { x: rect.x + w, y: rect.y, w: rect.w - w, h: rect.h };
    } else {
      const h = s / rect.w;
      let x = rect.x;
      for (const d of r) {
        const w = (d.v * scale) / h;
        out[d.i] = { x, y: rect.y, w, h };
        x += w;
      }
      rect = { x: rect.x, y: rect.y + h, w: rect.w, h: rect.h - h };
    }
  };
  for (const d of order) {
    const side = Math.min(rect.w, rect.h);
    if (row.length === 0 || worst([...row, d], side) <= worst(row, side)) row.push(d);
    else {
      layoutRow(row);
      row = [d];
    }
  }
  if (row.length) layoutRow(row);
  values.forEach((v, i) => {
    if (!out[i]) out[i] = { x: box.x, y: box.y, w: 0, h: 0 };
  });
  return out;
}

/**
 * Many parts of one whole, sized by area, optionally grouped one level. Good for spotting the few items that
 * dominate. Poor for precise comparison; use a bar chart when the exact ranking matters.
 */
export function Treemap({ data, label, value, group, format, height = 320, ...frame }: TreemapProps) {
  const { nodes, issues, groups, total } = useMemo(() => {
    const issues: Issue[] = [];
    if (!Array.isArray(data) || !data.length)
      return { nodes: [] as Node[], issues: [{ level: "error", message: "No data to display." }] as Issue[], groups: [] as string[], total: 0 };
    const nodes: Node[] = [];
    const bad: string[] = [];
    let skipped = 0;
    for (const row of data) {
      const r = readNum(row?.[value]);
      const name = String(row?.[label] ?? "");
      if (r.state === "invalid" || (r.value !== null && r.value < 0)) bad.push(name);
      else if (r.value === null || r.value === 0) skipped++;
      else nodes.push({ name, value: r.value, group: group ? String(row?.[group] ?? "Ungrouped") : undefined });
    }
    if (bad.length)
      issues.push({ level: "error", message: `Treemap sizes must be positive numbers. Check: ${bad.slice(0, 3).join(", ")}.` });
    if (skipped) issues.push({ level: "note", message: `${skipped} item(s) with zero or no value are not drawn.` });
    if (!bad.length && !nodes.length) issues.push({ level: "error", message: "Nothing to draw: every value is zero or missing." });
    const groups = group ? [...new Set(nodes.map((n) => n.group!))] : [];
    if (groups.length > 8)
      issues.push({ level: "warning", message: `${groups.length} groups exceed the 8-colour palette; extra groups are grey.` });
    return { nodes, issues, groups, total: nodes.reduce((a, n) => a + n.value, 0) };
  }, [data, label, value, group]);

  const groupColor = (g?: string) => (g === undefined ? tokens.series(0) : tokens.series(groups.indexOf(g)));
  const groupInk = (g?: string) => (g === undefined ? tokens.seriesInk(0) : tokens.seriesInk(groups.indexOf(g)));
  const legend = groups.map((g) => ({ key: g, label: g, color: groupColor(g) }));
  const table = {
    columns: [
      ...(group ? [{ key: "group", label: group }] : []),
      { key: "name", label },
      { key: "value", label: value, align: "right" as const, format: (v: unknown) => formatValue(v as number, format, { context: "table" }) },
      { key: "share", label: "Share", align: "right" as const, format: (v: unknown) => formatShare(v as number, 1) },
    ],
    rows: nodes.map((n) => ({ group: n.group, name: n.name, value: n.value, share: n.value / (total || 1) })),
  };
  if (group) table.columns = [table.columns[1], table.columns[0], ...table.columns.slice(2)];
  const top = [...nodes].sort((a, b) => b.value - a.value).slice(0, 3);
  const summary = `Treemap of ${nodes.length} items totalling ${formatValue(total, format)}. Largest: ${top
    .map((n) => `${n.name} ${formatShare(n.value / (total || 1))}`)
    .join(", ")}.`;

  return (
    <ChartFrame {...frame} height={height} issues={issues} table={table} summary={summary} legend={legend}>
      {({ width }) => <TreemapPlot width={width} height={height} nodes={nodes} groups={groups} total={total} format={format} groupColor={groupColor} groupInk={groupInk} grouped={!!group} />}
    </ChartFrame>
  );
}

function TreemapPlot({
  width,
  height,
  nodes,
  groups,
  total,
  format,
  groupColor,
  groupInk,
  grouped,
}: {
  width: number;
  height: number;
  nodes: Node[];
  groups: string[];
  total: number;
  format?: FormatInput;
  groupColor: (g?: string) => string;
  groupInk: (g?: string) => string;
  grouped: boolean;
}) {
  const { active, setActive, keyProps } = useActiveIndex(nodes.length);
  const GAP = 2;
  const fmtLabel = labelFormatter(format, nodes.map((n) => n.value));
  const rects: Rect[] = new Array(nodes.length);
  if (grouped) {
    const gTotals = groups.map((g) => nodes.filter((n) => n.group === g).reduce((a, n) => a + n.value, 0));
    const gRects = squarify(gTotals, { x: 0, y: 0, w: width, h: height });
    groups.forEach((g, gi) => {
      const idx = nodes.map((n, i) => (n.group === g ? i : -1)).filter((i) => i >= 0);
      const box = gRects[gi];
      const inner = squarify(
        idx.map((i) => nodes[i].value),
        { x: box.x + GAP, y: box.y + GAP, w: Math.max(0, box.w - GAP * 2), h: Math.max(0, box.h - GAP * 2) },
      );
      idx.forEach((i, k) => (rects[i] = inner[k]));
    });
  } else {
    squarify(
      nodes.map((n) => n.value),
      { x: 0, y: 0, w: width, h: height },
    ).forEach((r, i) => (rects[i] = r));
  }

  return (
    <>
      <svg width={width} height={height} role="group" aria-roledescription="chart" aria-label="Treemap. Use arrow keys to read items." {...keyProps}>
        {nodes.map((n, i) => {
          const r = rects[i];
          if (!r || r.w <= GAP || r.h <= GAP) return null;
          const x = r.x + GAP / 2;
          const y = r.y + GAP / 2;
          const w = r.w - GAP;
          const h = r.h - GAP;
          const fill = groupColor(n.group);
          const showName = w > 46 && h > 22;
          const showValue = w > 46 && h > 38;
          const valueText = fmtLabel(n.value);
          return (
            <g key={i} onPointerEnter={() => setActive(i)} onPointerLeave={() => setActive(null)}>
              <path d={roundedRect(x, y, w, h, 3)} style={{ fill }} className={`clui-mark${active !== null && active !== i ? " clui-dim" : ""}`} />
              {showName && (
                <text x={x + 7} y={y + 15} style={{ fill: groupInk(n.group), fontSize: 11.5, fontWeight: 600 }} aria-hidden>
                  {truncate(n.name, w - 12, 11.5)}
                </text>
              )}
              {showValue && textWidth(valueText, 11) < w - 12 && (
                <text x={x + 7} y={y + 30} style={{ fill: groupInk(n.group), fontSize: 11, opacity: 0.85 }} aria-hidden>
                  {valueText}
                </text>
              )}
            </g>
          );
        })}
      </svg>
      {active !== null && rects[active] && (
        <ChartTooltip
          x={rects[active].x + rects[active].w / 2}
          y={rects[active].y + rects[active].h / 2}
          width={width}
          height={height}
          data={{
            title: nodes[active].name,
            rows: [
              ...(nodes[active].group ? [{ label: "Group", value: nodes[active].group! }] : []),
              { label: "Value", value: formatValue(nodes[active].value, format, { context: "tooltip" }) },
              { label: "Share of total", value: formatShare(nodes[active].value / (total || 1), 1) },
            ],
          }}
        />
      )}
    </>
  );
}

Donut chart

One whole in up to six parts, with the total in the middle and a value legend.