Pie chart
Two to five parts of one whole, with a value-and-share legend.
One whole in up to six parts, with the total in the middle and a value legend.
<DonutChart />Donut chart is free under the MIT license.
$ npx shadcn@latest add https://chartslibraryui.com/r/donut-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
import { DonutChart } from "@/components/charts/donut-chart";
import { trafficSources } from "./sample-data";
export function Example() {
return (
<DonutChart
title="Half of visits come from organic search"
subtitle="Visits by source, last 30 days"
data={trafficSources}
label="source"
value="visits"
format="integer"
centerCaption="visits"
/>
);
}
Rows with a label key and a non-negative value key.
[{ source: "Organic search", visits: 48200 }, ...]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 DonutChartProps extends FrameProps {
data: Row[];
/** Key of the slice name. */
label: string;
/** Key of the slice value. Must be zero or positive. */
value: string;
format?: FormatInput;
/** Fold the smallest slices into "Other" beyond this many. Default 6. The fold is stated in a note. */
maxSlices?: number;
/** Text in the centre. Default: the total. Pass null to hide. */
centerLabel?: string | null;
/** Small caption under the centre value. */
centerCaption?: string;
/** Inner radius as a share of the outer radius. 0 draws a pie. Default 0.62. */
innerRadius?: number;
/** Slice names to emphasise; others are grey. */
highlight?: string | string[];
/** Name for the folded slice. */
otherLabel?: string;
}Installs donut-chart.tsx and the shared core/ (11 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, labelFormatter, type FormatInput } from "./core/format";
import { ChartFrame, ChartTooltip, KeySwatch, useActiveIndex, type FrameProps } from "./core/frame";
import { arcPath } from "./core/path";
export interface DonutChartProps extends FrameProps {
data: Row[];
/** Key of the slice name. */
label: string;
/** Key of the slice value. Must be zero or positive. */
value: string;
format?: FormatInput;
/** Fold the smallest slices into "Other" beyond this many. Default 6. The fold is stated in a note. */
maxSlices?: number;
/** Text in the centre. Default: the total. Pass null to hide. */
centerLabel?: string | null;
/** Small caption under the centre value. */
centerCaption?: string;
/** Inner radius as a share of the outer radius. 0 draws a pie. Default 0.62. */
innerRadius?: number;
/** Slice names to emphasise; others are grey. */
highlight?: string | string[];
/** Name for the folded slice. */
otherLabel?: string;
}
interface Slice {
name: string;
value: number;
share: number;
color: string;
folded?: number;
}
/**
* One whole in at most six parts, with the total in the middle. Slices keep their data order (sort your data if
* you want them ranked). Negative values are rejected because a share can't be negative.
*/
export function DonutChart({
data,
label,
value,
format,
maxSlices = 6,
centerLabel,
centerCaption,
innerRadius = 0.62,
highlight,
otherLabel = "Other",
height = 240,
...frame
}: DonutChartProps) {
const { slices, issues, total } = useMemo(() => {
const issues: Issue[] = [];
if (!Array.isArray(data) || data.length === 0)
return { slices: [] as Slice[], issues: [{ level: "error", message: "No data to display." }] as Issue[], total: 0 };
const items: { name: string; value: number }[] = [];
let missing = 0;
const negatives: string[] = [];
const invalid: string[] = [];
for (const row of data) {
const name = String(row?.[label] ?? "");
const r = readNum(row?.[value]);
if (r.state === "missing") missing++;
else if (r.state === "invalid") invalid.push(name);
else if (r.value! < 0) negatives.push(name);
else items.push({ name, value: r.value! });
}
if (invalid.length)
issues.push({ level: "error", message: `Non-numeric values for: ${invalid.slice(0, 3).join(", ")}.` });
if (negatives.length)
issues.push({
level: "error",
message: `Negative values can't be shown as shares of a whole (${negatives.slice(0, 3).join(", ")}). Use a bar chart.`,
});
if (missing) issues.push({ level: "warning", message: `${missing} slice(s) with no value are left out.` });
const total = items.reduce((a, b) => a + b.value, 0);
if (!issues.some((i) => i.level === "error") && total === 0)
issues.push({ level: "error", message: "All values are zero, so there is no whole to divide." });
const zeros = items.filter((d) => d.value === 0).length;
if (zeros) issues.push({ level: "note", message: `${zeros} slice(s) are zero and draw nothing.` });
let kept = items;
let folded: { name: string; value: number } | null = null;
if (items.length > maxSlices) {
const ranked = [...items].sort((a, b) => b.value - a.value);
const keep = new Set(ranked.slice(0, maxSlices - 1).map((d) => d.name));
kept = items.filter((d) => keep.has(d.name));
const rest = items.filter((d) => !keep.has(d.name));
folded = { name: otherLabel, value: rest.reduce((a, b) => a + b.value, 0) };
issues.push({
level: "note",
message: `${rest.length} smallest slices are combined into "${otherLabel}" (${formatShare(folded.value / (total || 1))}).`,
});
}
const hl = highlight === undefined ? null : new Set(Array.isArray(highlight) ? highlight : [highlight]);
let slot = 0;
const slices: Slice[] = kept.map((d) => ({
...d,
share: total ? d.value / total : 0,
color: hl ? (hl.has(d.name) ? tokens.series(slot++) : tokens.context) : tokens.series(slot++),
}));
if (folded)
slices.push({
...folded,
share: total ? folded.value / total : 0,
color: tokens.contextSoft,
folded: items.length - kept.length,
});
return { slices, issues, total };
}, [data, label, value, maxSlices, highlight, otherLabel]);
const table = {
columns: [
{ 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: slices.map((s) => ({ name: s.name, value: s.value, share: s.share })),
};
const summary = `${innerRadius > 0 ? "Donut" : "Pie"} chart of ${slices.length} parts totalling ${formatValue(
total,
format,
)}. ${slices
.slice(0, 6)
.map((s) => `${s.name} ${formatShare(s.share)}`)
.join(", ")}.`;
return (
<ChartFrame {...frame} height={height} issues={issues} table={table} summary={summary}>
{({ width }) => (
<DonutPlot
width={width}
height={height}
slices={slices}
total={total}
format={format}
inner={innerRadius}
centerLabel={centerLabel}
centerCaption={centerCaption}
/>
)}
</ChartFrame>
);
}
function DonutPlot({
width,
height,
slices,
total,
format,
inner,
centerLabel,
centerCaption,
}: {
width: number;
height: number;
slices: Slice[];
total: number;
format?: FormatInput;
inner: number;
centerLabel?: string | null;
centerCaption?: string;
}) {
const { active, setActive, keyProps } = useActiveIndex(slices.length);
const stacked = width < 440;
const size = stacked ? Math.min(width, height) : Math.min(height, width * 0.45);
const outer = size / 2 - 4;
const ir = outer * Math.max(0, Math.min(0.9, inner));
const cx = stacked ? width / 2 : size / 2;
const cy = size / 2;
const gap = slices.length > 1 ? 0.012 : 0; // surface gap between slices, in radians at the outer edge
const arcs: (Slice & { a0: number; a1: number; mid: number })[] = [];
for (let i = 0, angle = 0; i < slices.length; i++) {
const sl = slices[i];
const sweep = sl.share * Math.PI * 2;
const pad = sweep > gap * 2 ? gap / 2 : 0;
arcs.push({ ...sl, a0: angle + pad, a1: angle + sweep - pad, mid: angle + sweep / 2 });
angle += sweep;
}
const center = centerLabel === undefined ? formatValue(total, format) : centerLabel;
return (
<div style={{ display: "flex", flexDirection: stacked ? "column" : "row", gap: stacked ? 12 : 28, alignItems: stacked ? "stretch" : "center" }}>
<div style={{ position: "relative", width: stacked ? width : size, height: size, flexShrink: 0 }}>
<svg width={stacked ? width : size} height={size} role="group" aria-roledescription="chart" aria-label="Use arrow keys to read each part." {...keyProps}>
{arcs.map((a, i) => (
<path
key={a.name + i}
d={arcPath(cx, cy, ir, active === i ? outer + 3 : outer, a.a0, a.a1)}
style={{ fill: a.color }}
className={`clui-mark${active !== null && active !== i ? " clui-dim" : ""}`}
onPointerEnter={() => setActive(i)}
onPointerLeave={() => setActive(null)}
/>
))}
{ir > 24 && center !== null && (
<g aria-hidden>
<text x={cx} y={cy} dy={centerCaption ? "-0.1em" : "0.35em"} textAnchor="middle" className="clui-label-strong" style={{ fontSize: Math.min(22, ir / 2.6) }}>
{center}
</text>
{centerCaption && (
<text x={cx} y={cy} dy="1.4em" textAnchor="middle" className="clui-annot">
{centerCaption}
</text>
)}
</g>
)}
</svg>
{active !== null && arcs[active] && (
<ChartTooltip
x={cx + Math.sin(arcs[active].mid) * outer * 0.8}
y={cy - Math.cos(arcs[active].mid) * outer * 0.8}
width={stacked ? width : size * 2}
height={size}
data={{
title: arcs[active].name,
rows: [
{ label: "Value", value: formatValue(arcs[active].value, format, { context: "tooltip" }) },
{ label: "Share", value: formatShare(arcs[active].share, 1) },
],
footer: arcs[active].folded ? `${arcs[active].folded} smaller parts combined` : undefined,
}}
/>
)}
</div>
<ul className="clui-legend" style={{ flexDirection: "column", gap: 6, margin: 0, flex: 1, minWidth: 0 }} aria-hidden>
{arcs.map((a, i, all) => (
<li
key={a.name + i}
style={{ display: "grid", gridTemplateColumns: "auto 1fr auto auto", gap: 8, alignItems: "center", opacity: active !== null && active !== i ? 0.5 : 1 }}
onPointerEnter={() => setActive(i)}
onPointerLeave={() => setActive(null)}
>
<KeySwatch color={a.color} />
<span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", color: "var(--clui-ink)" }} title={a.name}>
{a.name}
</span>
<span style={{ fontVariantNumeric: "tabular-nums" }}>{labelFormatter(format, all.map((x) => x.value))(a.value)}</span>
<span style={{ fontVariantNumeric: "tabular-nums", minWidth: 36, textAlign: "right", color: "var(--clui-ink)" }}>{formatShare(a.share)}</span>
</li>
))}
</ul>
</div>
);
}
Two to five parts of one whole, with a value-and-share legend.
A countable part-to-whole: one square is one percent.
Many parts of one whole, sized by area and optionally grouped.