Diverging bar chart
Positive and negative changes either side of zero, coloured by business direction.
Two distributions back to back on one shared scale, such as headcount by age and gender.
<PopulationPyramid />A population pyramid compares two distributions across the same bands, drawn back to back: one group to the left of the centre, the other to the right. The classic use is a country's population by age and sex, but it works for any two groups across ordered bands, such as a company's headcount by age group for women and men.
Both sides use one shared scale, so a longer bar is always a bigger number and the shape can be compared honestly. Band names sit in the centre column. Switch to shares to show each value as a part of the grand total, which helps when the groups differ in size. Negative or missing values are noted, never drawn as zero.
Use it for the shape of two groups across bands. For one group, use a histogram; for bands without an order, a grouped bar chart.
Population pyramid is free under the MIT license.
pnpm dlx shadcn@latest add https://chartslibraryui.com/r/population-pyramid.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 population pyramid for your AI tool and attach it to Claude, ChatGPT, Lovable or Cursor. No terminal needed. How it works
import { PopulationPyramid } from "@/components/charts/population-pyramid";
import { workforceByAge } from "./sample-data";
export function Example() {
return (
<PopulationPyramid
title="Four in ten employees are between 25 and 34"
subtitle="Headcount by age group and gender, December 2026"
data={workforceByAge}
label="age"
left="women"
right="men"
leftLabel="Women"
rightLabel="Men"
format="integer"
/>
);
}
One row per band (youngest first) with a label key and two numeric keys, one per side.
[{ age: "25–29", women: 128, men: 151 }, ...]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 PopulationPyramidProps extends FrameProps {
/** Rows to draw, one per band (e.g. age group). See the Data section for the shape. */
data: Row[];
/** Key of the band name, e.g. "25–29". */
label: string;
/** Key of the values drawn to the left of the centre. */
left: string;
/** Key of the values drawn to the right of the centre. */
right: string;
/** Text for the left values in the legend, tooltip and table. Default: the key. */
leftLabel?: string;
/** Text for the right values in the legend, tooltip and table. Default: the key. */
rightLabel?: string;
/** Number format for values: "currency", "percent", "integer", "compact" or a format object. */
format?: FormatInput;
/** Draw each value as a share of the grand total instead of its count. Default false. */
share?: boolean;
/** "bottom-up" (default) draws the first row at the bottom, like an age pyramid. "top-down" keeps the data order. */
order?: "bottom-up" | "top-down";
/** Print the value at the end of each bar. Default: on for up to 12 bands. */
showValues?: boolean;
}Installs population-pyramid.tsx and the shared core/ (12 files).
"use client";
import { useMemo, type PointerEvent } from "react";
import { AXIS_FONT } from "./core/axis";
import { color as tokens } from "./core/color";
import { readNum, type Issue, type Row } from "./core/data";
import { formatShare, formatValue, labelFormatter, tickFormatter, type FormatInput } from "./core/format";
import { ChartFrame, ChartTooltip, localPoint, useActiveIndex, type FrameProps, type LegendItem } from "./core/frame";
import { barPath } from "./core/path";
import { bandScale, linearScale, valueDomain } from "./core/scale";
import { textWidth, truncate } from "./core/text";
import { useWords } from "./core/words";
export interface PopulationPyramidProps extends FrameProps {
/** Rows to draw, one per band (e.g. age group). See the Data section for the shape. */
data: Row[];
/** Key of the band name, e.g. "25–29". */
label: string;
/** Key of the values drawn to the left of the centre. */
left: string;
/** Key of the values drawn to the right of the centre. */
right: string;
/** Text for the left values in the legend, tooltip and table. Default: the key. */
leftLabel?: string;
/** Text for the right values in the legend, tooltip and table. Default: the key. */
rightLabel?: string;
/** Number format for values: "currency", "percent", "integer", "compact" or a format object. */
format?: FormatInput;
/** Draw each value as a share of the grand total instead of its count. Default false. */
share?: boolean;
/** "bottom-up" (default) draws the first row at the bottom, like an age pyramid. "top-down" keeps the data order. */
order?: "bottom-up" | "top-down";
/** Print the value at the end of each bar. Default: on for up to 12 bands. */
showValues?: boolean;
}
interface Band {
name: string;
l: number | null;
r: number | null;
row: Row;
}
/**
* Two distributions back to back on one shared scale, such as headcount by age group for women and men. The
* centre column holds the band names; both sides use the same axis so their lengths compare honestly.
*/
export function PopulationPyramid({ data, label, left, right, leftLabel, rightLabel, format, share = false, order = "bottom-up", showValues, height: hProp, ...frame }: PopulationPyramidProps) {
const L = useWords(frame.words);
const prep = useMemo(() => {
const issues: Issue[] = [];
if (!Array.isArray(data) || !data.length) return { bands: [] as Band[], total: 0, issues: [{ level: "error", message: "No data to display." }] as Issue[] };
let invalid = 0;
let negative = 0;
let missing = 0;
const bands: Band[] = data.map((r) => {
const read = (k: string) => {
const n = readNum(r?.[k]);
if (n.state === "invalid") {
invalid++;
return null;
}
if (n.value === null) {
missing++;
return null;
}
if (n.value < 0) {
negative++;
return null;
}
return n.value;
};
return { name: String(r?.[label] ?? ""), l: read(left), r: read(right), row: r };
});
if (invalid) issues.push({ level: "error", message: `${invalid} value(s) in "${left}" or "${right}" are not numbers. Convert to numbers before charting.` });
if (negative) issues.push({ level: "note", message: `${negative} negative value(s) are not drawn; a pyramid shows counts or shares.` });
if (missing) issues.push({ level: "note", message: `${missing} missing value(s) are left empty, not drawn as zero.` });
const total = bands.reduce((s, b) => s + (b.l ?? 0) + (b.r ?? 0), 0);
if (!invalid && total <= 0) issues.push({ level: "warning", message: "Every value is zero or missing." });
return { bands: order === "bottom-up" ? [...bands].reverse() : bands, total, issues };
}, [data, label, left, right, order]);
const { bands, total } = prep;
const lLabel = leftLabel ?? left;
const rLabel = rightLabel ?? right;
const shown = (v: number | null) => (v === null ? null : share ? (total > 0 ? v / total : 0) : v);
const fmt: FormatInput | undefined = share ? "percent" : format;
const height = hProp ?? Math.max(160, bands.length * 22 + 36);
const legend: LegendItem[] = [
{ key: "l", label: lLabel, color: tokens.series(0), shape: "square" },
{ key: "r", label: rLabel, color: tokens.series(1), shape: "square" },
];
const f = (v: unknown) => formatValue(v as number, format, { context: "table" });
const table = {
columns: [
{ key: "name", label },
{ key: "l", label: lLabel, align: "right" as const, format: f },
{ key: "r", label: rLabel, align: "right" as const, format: f },
{ key: "s", label: L.share, align: "right" as const, format: (v: unknown) => formatShare(v as number, 1) },
],
rows: [...bands].reverse().map((b) => ({ name: b.name, l: b.l, r: b.r, s: total > 0 ? ((b.l ?? 0) + (b.r ?? 0)) / total : null })),
};
const sumL = bands.reduce((s, b) => s + (b.l ?? 0), 0);
const summary = `Population pyramid of ${bands.length} bands. ${lLabel} ${formatValue(sumL, format)} (${formatShare(total > 0 ? sumL / total : 0)}), ${rLabel} ${formatValue(
total - sumL,
format,
)} (${formatShare(total > 0 ? (total - sumL) / total : 0)}).`;
return (
<ChartFrame {...frame} height={height} issues={prep.issues} table={table} summary={summary} legend={legend}>
{({ width }) => <Plot {...{ width, height, bands, shown, fmt, format, lLabel, rLabel, total, showValues: showValues ?? bands.length <= 12 }} />}
</ChartFrame>
);
}
function Plot(p: {
width: number;
height: number;
bands: Band[];
shown: (v: number | null) => number | null;
fmt?: FormatInput;
format?: FormatInput;
lLabel: string;
rLabel: string;
total: number;
showValues: boolean;
}) {
const L = useWords();
const { width, height, bands } = p;
const { active, setActive, keyProps } = useActiveIndex(bands.length, { describe: (i) => ({ label: bands[i]?.name, row: bands[i]?.row }) });
const vals = bands.flatMap((b) => [p.shown(b.l), p.shown(b.r)]).filter((v): v is number => v !== null);
const { domain, ticks } = valueDomain(vals.length ? vals : [0], { includeZero: true, ticks: Math.max(2, Math.floor(width / 220)) });
const maxV = Math.max(domain[1], 1e-12);
const lf = labelFormatter(p.fmt, vals);
const ft = tickFormatter(p.fmt, ticks);
const colW = Math.min(width * 0.22, Math.max(...bands.map((b) => textWidth(b.name, AXIS_FONT)), 24) + 20);
const valueW = p.showValues ? Math.max(0, ...vals.map((v) => textWidth(lf(v), AXIS_FONT))) + 8 : 6;
const cx = width / 2;
const top = 2;
const bottom = height - 22;
const band = bandScale(bands.length, [top, bottom], { paddingInner: 0.18, paddingOuter: 0.06 });
const half = Math.max(10, cx - colW / 2 - valueW);
const xr = linearScale([0, maxV], [cx + colW / 2, cx + colW / 2 + half]);
const xl = linearScale([0, maxV], [cx - colW / 2, cx - colW / 2 - half]);
const onMove = (e: PointerEvent<SVGRectElement>) => setActive(band.indexAt(localPoint(e).y + top));
const a = active !== null ? bands[active] : null;
return (
<>
<svg width={width} height={height} role="group" aria-roledescription="chart" aria-label="Population pyramid. Use arrow keys to read bands." {...keyProps}>
{ticks
.filter((t) => t >= 0)
.map((t, i) => (
<g key={i} aria-hidden>
{[xl(t), xr(t)].map((xx, k) =>
t === 0 && k === 1 ? null : (
<g key={k}>
<line x1={xx} x2={xx} y1={top} y2={bottom} style={{ stroke: t === 0 ? "var(--clui-axis)" : "var(--clui-grid)" }} />
<text x={xx} y={bottom + 16} textAnchor="middle" className="clui-tick">
{ft(t)}
</text>
</g>
),
)}
</g>
))}
<line x1={xr(0)} x2={xr(0)} y1={top} y2={bottom} style={{ stroke: "var(--clui-axis)" }} aria-hidden />
{bands.map((b, i) => {
const y = band(i);
const h = band.bandwidth;
const lv = p.shown(b.l);
const rv = p.shown(b.r);
return (
<g key={i} className={`clui-mark${active !== null && active !== i ? " clui-dim" : ""}`}>
<text x={cx} y={y + h / 2} dy="0.32em" textAnchor="middle" className="clui-tick" style={{ fill: "var(--clui-ink)" }}>
{truncate(b.name, colW - 8, AXIS_FONT)}
</text>
{lv !== null && lv > 0 && <path d={barPath(xl(lv), y, xl(0) - xl(lv), h, 3, "left")} style={{ fill: tokens.series(0) }} />}
{rv !== null && rv > 0 && <path d={barPath(xr(0), y, xr(rv) - xr(0), h, 3, "right")} style={{ fill: tokens.series(1) }} />}
{p.showValues && lv !== null && (
<text x={xl(lv) - 4} y={y + h / 2} dy="0.32em" textAnchor="end" className="clui-label">
{lf(lv)}
</text>
)}
{p.showValues && rv !== null && (
<text x={xr(rv) + 4} y={y + h / 2} dy="0.32em" className="clui-label">
{lf(rv)}
</text>
)}
</g>
);
})}
<rect x={0} y={top} width={width} height={Math.max(0, bottom - top)} fill="transparent" onPointerMove={onMove} onPointerLeave={() => setActive(null)} />
</svg>
{a && (
<ChartTooltip
x={cx}
y={band(active!) + band.bandwidth / 2}
width={width}
height={height}
data={{
title: a.name,
rows: [
{ label: p.lLabel, value: formatValue(a.l, p.format, { context: "tooltip" }), color: tokens.series(0), shape: "square", note: a.l !== null && p.total > 0 ? `(${formatShare(a.l / p.total, 1)})` : undefined },
{ label: p.rLabel, value: formatValue(a.r, p.format, { context: "tooltip" }), color: tokens.series(1), shape: "square", note: a.r !== null && p.total > 0 ? `(${formatShare(a.r / p.total, 1)})` : undefined },
{ label: L.total, value: formatValue((a.l ?? 0) + (a.r ?? 0), p.format, { context: "tooltip" }), strong: true },
],
}}
/>
)}
</>
);
}
Positive and negative changes either side of zero, coloured by business direction.
The shape of one distribution, with automatic binning and a median marker.
Two to four measures side by side per category.