Treemap
Many parts of one whole, sized by area and optionally grouped.
A total broken down two or three levels deep, drawn as rings from the centre out.
<SunburstChart />A sunburst chart shows a total and how it splits, level by level. The centre ring is the first level, for example regions; each ring outwards splits its parent, for example countries within a region, then segments within a country.
You pass flat rows, one per item at the outermost level, and list the keys of the levels from the centre out. The chart sums the parents for you, sorts each ring by size and keeps each branch in the colour of its top-level group. Names are printed where they fit; the rest are in the tooltip, which gives the value, the share of the total and the share of the parent. The total sits in the middle.
Use it when the shape of a hierarchy is the story: which region dominates, and which country drives it. For precise comparisons between items, a bar chart reads better; for many small items at one level, use a treemap.
Sunburst chart is free under the MIT license.
pnpm dlx shadcn@latest add https://chartslibraryui.com/r/sunburst-chart.jsonInstalls 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
Building with an AI tool? Download the sunburst chart for your AI tool and attach it to Claude, ChatGPT, Lovable or Cursor. No terminal needed. How it works
import { SunburstChart } from "@/components/charts/sunburst-chart";
import { spendTreemap } from "./sample-data";
export function Example() {
return (
<SunburstChart
title="Infrastructure is 43% of software spend"
subtitle="Annual software spend by category and vendor, USD"
data={spendTreemap}
levels={["group", "name"]}
value="value"
format="currency"
/>
);
}
One row per item at the outermost level, with one key per level and a positive numeric value; parents are summed for you.
[{ region: "Europe", country: "Germany", revenue: 610000 }, ...]Missing values are null. Invalid values make the chart say what’s wrong instead of drawing a misleading picture. How charts handle bad data
Every chart also accepts the shared frame props: title, subtitle, source, height, mode, toolbar. Common API
export interface SunburstChartProps extends FrameProps {
/** Rows to draw, one object per row (the outermost level). See the Data section for the shape. */
data: Row[];
/** Keys of the hierarchy levels, from the centre outwards, e.g. ["department", "team"]. Up to 3 levels. */
levels: string[];
/** Key of the size of each row. Must be positive. */
value: string;
/** Number format for values: "currency", "percent", "integer", "compact" or a format object. */
format?: FormatInput;
/** Sort each ring by size. Default true; set false to keep the data order. */
sort?: boolean;
/** Text under the total in the centre. Default "Total". */
centerLabel?: string;
}Installs sunburst-chart.tsx and the shared core/ (12 files).
"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, type FormatInput } from "./core/format";
import { ChartFrame, ChartTooltip, useActiveIndex, type FrameProps, type LegendItem } from "./core/frame";
import { arcPath } from "./core/path";
import { textWidth, truncate } from "./core/text";
import { useWords } from "./core/words";
export interface SunburstChartProps extends FrameProps {
/** Rows to draw, one object per row (the outermost level). See the Data section for the shape. */
data: Row[];
/** Keys of the hierarchy levels, from the centre outwards, e.g. ["department", "team"]. Up to 3 levels. */
levels: string[];
/** Key of the size of each row. Must be positive. */
value: string;
/** Number format for values: "currency", "percent", "integer", "compact" or a format object. */
format?: FormatInput;
/** Sort each ring by size. Default true; set false to keep the data order. */
sort?: boolean;
/** Text under the total in the centre. Default "Total". */
centerLabel?: string;
}
interface Node {
name: string;
value: number;
depth: number;
parent: number;
path: string[];
slot: number;
a0: number;
a1: number;
}
interface Tree {
name: string;
value: number;
order: number;
children: Map<string, Tree>;
}
const LABEL_FONT = 11;
/**
* A hierarchy as rings: the centre ring is the top level, each ring outwards splits its parent. Use it for a
* total broken down two or three levels deep, such as spend by department and team.
*/
export function SunburstChart({ data, levels, value, format, sort = true, centerLabel, height: hProp, ...frame }: SunburstChartProps) {
const L = useWords(frame.words);
const levelSig = (levels ?? []).join("|");
const prep = useMemo(() => {
const issues: Issue[] = [];
const lv = (levels ?? []).slice(0, 3);
if (!Array.isArray(data) || !data.length) return { nodes: [] as Node[], total: 0, depth: 0, issues: [{ level: "error", message: "No data to display." }] as Issue[] };
if (!lv.length) return { nodes: [] as Node[], total: 0, depth: 0, issues: [{ level: "error", message: "Pass at least one key in `levels`." }] as Issue[] };
if ((levels ?? []).length > 3) issues.push({ level: "note", message: "Only the first 3 levels are drawn." });
const root: Tree = { name: "", value: 0, order: 0, children: new Map() };
let invalid = 0;
let missing = 0;
let nonPositive = 0;
let order = 0;
for (const r of data) {
const n = readNum(r?.[value]);
if (n.state === "invalid") {
invalid++;
continue;
}
if (n.value === null) {
missing++;
continue;
}
if (n.value <= 0) {
nonPositive++;
continue;
}
root.value += n.value;
let node = root;
for (const key of lv) {
const raw = r?.[key];
const name = raw === null || raw === undefined || String(raw).trim() === "" ? "(blank)" : String(raw);
let child = node.children.get(name);
if (!child) {
child = { name, value: 0, order: order++, children: new Map() };
node.children.set(name, child);
}
child.value += n.value;
node = child;
}
}
if (invalid) issues.push({ level: "error", message: `"${value}" has ${invalid} non-numeric value(s). Convert to numbers before charting.` });
if (missing) issues.push({ level: "note", message: `${missing} row(s) without a value are not drawn.` });
if (nonPositive) issues.push({ level: "note", message: `${nonPositive} row(s) with zero or negative values are not drawn; a sunburst shows parts of a positive total.` });
if (!invalid && root.value <= 0) issues.push({ level: "error", message: "No positive values to display." });
const nodes: Node[] = [];
const walk = (t: Tree, depth: number, a0: number, a1: number, parent: number, slot: number, path: string[]) => {
const kids = [...t.children.values()].sort(sort ? (a, b) => b.value - a.value || a.order - b.order : (a, b) => a.order - b.order);
let a = a0;
kids.forEach((c, i) => {
const span = t.value > 0 ? (a1 - a0) * (c.value / t.value) : 0;
const s = depth === 0 ? i : slot;
const idx = nodes.length;
nodes.push({ name: c.name, value: c.value, depth, parent, path: [...path, c.name], slot: s, a0: a, a1: a + span });
walk(c, depth + 1, a, a + span, idx, s, [...path, c.name]);
a += span;
});
};
if (root.value > 0) walk(root, 0, 0, Math.PI * 2, -1, 0, []);
return { nodes, total: root.value, depth: lv.length, issues };
}, [data, levelSig, value, sort]); // eslint-disable-line react-hooks/exhaustive-deps
const { nodes, total, depth } = prep;
const lv = (levels ?? []).slice(0, 3);
const top = nodes.filter((n) => n.depth === 0);
const leaves = nodes.filter((n) => n.depth === depth - 1);
const height = hProp ?? 340;
const legend: LegendItem[] | undefined =
top.length > 1 ? top.slice(0, 8).map((n) => ({ key: n.name, label: n.name, color: tokens.series(n.slot), shape: "square" as const })) : undefined;
const f = (v: unknown) => formatValue(v as number, format, { context: "table" });
const table = {
columns: [
...lv.map((k, i) => ({ key: `l${i}`, label: k })),
{ key: "value", label: value, align: "right" as const, format: f },
{ key: "share", label: L.share, align: "right" as const, format: (v: unknown) => formatShare(v as number, 1) },
],
rows: leaves.map((n) => ({ ...Object.fromEntries(n.path.map((p, i) => [`l${i}`, p])), value: n.value, share: total > 0 ? n.value / total : null })),
};
const summary = `Sunburst chart: total ${formatValue(total, format)} in ${top.length} group(s) and ${leaves.length} item(s). ${top
.slice(0, 5)
.map((n) => `${n.name} ${formatShare(total > 0 ? n.value / total : 0)}`)
.join(", ")}.`;
return (
<ChartFrame {...frame} height={height} issues={prep.issues} table={table} summary={summary} legend={legend}>
{({ width }) => <Rings {...{ width, height, nodes, total, depth, format, centerLabel: centerLabel ?? L.total }} />}
</ChartFrame>
);
}
function Rings(p: { width: number; height: number; nodes: Node[]; total: number; depth: number; format?: FormatInput; centerLabel: string }) {
const L = useWords();
const { width, height, nodes, total, depth } = p;
const { active, setActive, keyProps } = useActiveIndex(nodes.length, { describe: (i) => ({ label: nodes[i]?.path.join(" / ") }) });
const cx = width / 2;
const cy = height / 2;
const R = Math.max(40, Math.min(width, height) / 2 - 4);
const hole = R * 0.34;
const ring = (R - hole) / Math.max(1, depth);
const radii = (d: number) => [hole + d * ring, hole + (d + 1) * ring] as const;
const lineage = new Set<number>();
if (active !== null) for (let i: number = active; i >= 0; i = nodes[i].parent) lineage.add(i);
const descendantOfActive = (i: number) => {
if (active === null) return false;
for (let k = nodes[i].parent; k >= 0; k = nodes[k].parent) if (k === active) return true;
return false;
};
const centroid = (n: Node) => {
const [r0, r1] = radii(n.depth);
const m = (n.a0 + n.a1) / 2;
const rm = (r0 + r1) / 2;
return { x: cx + rm * Math.sin(m), y: cy - rm * Math.cos(m), rm };
};
const a = active !== null ? nodes[active] : null;
const parentValue = a && a.parent >= 0 ? nodes[a.parent].value : total;
return (
<>
<svg width={width} height={height} role="group" aria-roledescription="chart" aria-label="Sunburst chart. Use arrow keys to read segments." {...keyProps}>
{nodes.map((n, i) => {
const [r0, r1] = radii(n.depth);
const on = active === null || lineage.has(i) || descendantOfActive(i);
const fill = tokens.series(n.slot);
return (
<path
key={i}
d={arcPath(cx, cy, r0, r1, n.a0, n.a1)}
className={`clui-mark${on ? "" : " clui-dim"}`}
style={{ fill, fillOpacity: n.depth === 0 ? 1 : 0.72 - (n.depth - 1) * 0.16, stroke: "var(--clui-surface)" }}
strokeWidth={1.5}
onPointerEnter={() => setActive(i)}
onPointerLeave={() => setActive(null)}
/>
);
})}
{nodes.map((n, i) => {
const { x, y } = centroid(n);
const [r0, r1] = radii(n.depth);
if (r1 - r0 < 16) return null;
// a horizontal label fits when its box stays inside the ring and inside the segment's angles
const full = n.a1 - n.a0 >= Math.PI * 2 - 1e-6;
const fits = (w: number) => {
for (const dx of [-w / 2, -w / 4, 0, w / 4, w / 2])
for (const dy of [-6, 6]) {
const px = x + dx - cx;
const py = y + dy - cy;
const r = Math.hypot(px, py);
if (r < r0 + 3 || r > r1 - 3) return false;
if (full) continue;
let ang = Math.atan2(px, -py);
if (ang < 0) ang += Math.PI * 2;
if (ang < n.a0 + 0.01 || ang > n.a1 - 0.01) return false;
}
return true;
};
const w = textWidth(n.name, LABEL_FONT);
let rot: number | null = null;
if (!fits(w)) {
// otherwise along the ring (tangential), turned so it never reads upside down
const rm = (r0 + r1) / 2;
const half = Math.atan2(w / 2 + 3, rm - 6);
const ok = (full || half * 2 <= n.a1 - n.a0 - 0.04) && Math.hypot(rm + 6, w / 2) <= r1 - 2;
if (!ok) return null;
let deg = (((n.a0 + n.a1) / 2) * 180) / Math.PI;
if (deg > 90 && deg < 270) deg -= 180;
rot = deg;
}
const text = n.name;
return (
<text
key={`t${i}`}
x={x}
y={y}
dy="0.32em"
textAnchor="middle"
transform={rot !== null ? `rotate(${rot.toFixed(1)} ${x} ${y})` : undefined}
className="clui-label"
aria-hidden
style={{ fill: n.depth === 0 ? tokens.seriesInk(n.slot) : "var(--clui-ink)", pointerEvents: "none" }}
>
{text}
</text>
);
})}
<g aria-hidden style={{ pointerEvents: "none" }}>
<text x={cx} y={cy - 4} textAnchor="middle" className="clui-label-strong" style={{ fontSize: Math.max(13, Math.min(22, hole * 0.34)) }}>
{a ? formatShare(total > 0 ? a.value / total : 0, 1) : formatValue(total, p.format)}
</text>
<text x={cx} y={cy + 14} textAnchor="middle" className="clui-annot">
{truncate(a ? a.name : p.centerLabel, hole * 1.7, LABEL_FONT)}
</text>
</g>
</svg>
{a && (
<ChartTooltip
x={centroid(a).x}
y={centroid(a).y}
width={width}
height={height}
data={{
title: a.path.join(" / "),
rows: [
{ label: L.value, value: formatValue(a.value, p.format, { context: "tooltip" }), color: tokens.series(a.slot), shape: "square", strong: true },
{ label: `${L.share} (${L.total.toLowerCase()})`, value: formatShare(total > 0 ? a.value / total : 0, 1) },
...(a.parent >= 0 ? [{ label: `${L.share} (${nodes[a.parent].name})`, value: formatShare(parentValue > 0 ? a.value / parentValue : 0, 1) }] : []),
],
}}
/>
)}
</>
);
}
Many parts of one whole, sized by area and optionally grouped.
One whole in up to six parts, with the total in the middle and a value legend.
Two levels of share: column width by group size, segments by mix inside each group.