Stacked bar chart
Totals and their parts, with negatives stacked below zero.
Survey answers as diverging stacked bars centred on neutral, with a net score per row. NPS-ready.
<LikertChart />A Likert chart shows answers on an ordered scale (strongly disagree to strongly agree) as diverging stacked bars. Negative answers run to the left of a centre line and positive answers to the right, with the neutral answer split across the centre. Rows line up on that centre, so you compare agreement at a glance instead of hunting along stacked bars.
Pass counts or shares per answer; each row is turned into shares of its own total, so questions with different numbers of responses compare fairly. The net score (positive share minus negative share, in points) is printed at the right in good or bad colour, and you can sort by it. Colours come from the diverging palette, with grey for neutral.
For Net Promoter Score, pass detractors, passives and promoters and name the net score NPS: the number printed is the NPS. For one question alone, a single stacked bar is enough.
Likert chart is free under the MIT license.
pnpm dlx shadcn@latest add https://chartslibraryui.com/r/likert-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 likert chart for your AI tool and attach it to Claude, ChatGPT, Lovable or Cursor. No terminal needed. How it works
import { LikertChart } from "@/components/charts/likert-chart";
import { engagementSurvey } from "./sample-data";
export function Example() {
return (
<LikertChart
title="Workload and how decisions are explained score lowest"
subtitle="Employee survey, share of answers per statement, 265 responses"
data={engagementSurvey}
label="question"
responses={["sd", "d", "n", "a", "sa"]}
responseLabels={["Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"]}
/>
);
}
One row per question with a label key and one numeric key per answer (counts or shares), from most negative to most positive.
[{ question: "I understand our goals", sd: 6, d: 14, n: 31, a: 118, sa: 96 }, ...]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 LikertChartProps extends FrameProps {
/** Rows to draw, one per question or item. See the Data section for the shape. */
data: Row[];
/** Key of the question or item name. */
label: string;
/** Keys of the answer counts (or shares), from the most negative answer to the most positive. 2 to 7 keys. */
responses: string[];
/** Display names for the answers, in the same order. Default: the keys. */
responseLabels?: string[];
/** Sort rows by net score, highest first. Default "none" keeps the data order. */
sort?: "none" | "net";
/** Name of the net score: positive share minus negative share, in points. Default "Net". Use "NPS" for Net Promoter Score. */
netLabel?: string;
/** Show the net score at the right of each row. Default true. */
showNet?: boolean;
}Installs likert-chart.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, toneOf, toneText } from "./core/color";
import { readNum, type Issue, type Row } from "./core/data";
import { formatShare, formatValue } from "./core/format";
import { ChartFrame, ChartTooltip, localPoint, useActiveIndex, type FrameProps, type LegendItem, type TooltipRow } from "./core/frame";
import { bandScale, linearScale } from "./core/scale";
import { textWidth, truncate } from "./core/text";
export interface LikertChartProps extends FrameProps {
/** Rows to draw, one per question or item. See the Data section for the shape. */
data: Row[];
/** Key of the question or item name. */
label: string;
/** Keys of the answer counts (or shares), from the most negative answer to the most positive. 2 to 7 keys. */
responses: string[];
/** Display names for the answers, in the same order. Default: the keys. */
responseLabels?: string[];
/** Sort rows by net score, highest first. Default "none" keeps the data order. */
sort?: "none" | "net";
/** Name of the net score: positive share minus negative share, in points. Default "Net". Use "NPS" for Net Promoter Score. */
netLabel?: string;
/** Show the net score at the right of each row. Default true. */
showNet?: boolean;
}
interface Item {
name: string;
counts: (number | null)[];
shares: number[];
total: number;
net: number;
row: Row;
}
const FONT = 11;
/** Diverging colour step for answer i of k: negatives left of centre, a neutral middle for odd scales. */
const STEPS: Record<number, number[]> = {
2: [-2, 2],
3: [-2, 0, 2],
4: [-2, -1, 1, 2],
5: [-2, -1, 0, 1, 2],
6: [-3, -2, -1, 1, 2, 3],
7: [-3, -2, -1, 0, 1, 2, 3],
};
function stepOf(i: number, k: number): number {
return STEPS[Math.max(2, Math.min(7, k))]?.[i] ?? 0;
}
/**
* Survey answers as diverging stacked bars centred on the neutral point: disagreement to the left, agreement to the
* right, so rows compare at a glance. Works for agree/disagree scales and for NPS (detractors, passives, promoters).
*/
export function LikertChart({ data, label, responses, responseLabels, sort = "none", netLabel = "Net", showNet = true, height: hProp, ...frame }: LikertChartProps) {
const keys = (responses ?? []).slice(0, 7);
const names = keys.map((k, i) => responseLabels?.[i] ?? k);
const sig = keys.join("|");
const prep = useMemo(() => {
const issues: Issue[] = [];
if (!Array.isArray(data) || !data.length) return { items: [] as Item[], issues: [{ level: "error", message: "No data to display." }] as Issue[] };
if (keys.length < 2) return { items: [] as Item[], issues: [{ level: "error", message: "Pass at least 2 answer keys in `responses`." }] as Issue[] };
if ((responses ?? []).length > 7) issues.push({ level: "note", message: "Only the first 7 answers are drawn." });
const k = keys.length;
const half = Math.floor(k / 2);
let invalid = 0;
let empty = 0;
let negative = 0;
let items: Item[] = [];
for (const r of data) {
const counts = keys.map((key) => {
const n = readNum(r?.[key]);
if (n.state === "invalid") invalid++;
if (n.value !== null && n.value < 0) {
negative++;
return null;
}
return n.value;
});
const total = counts.reduce<number>((s, v) => s + (v ?? 0), 0);
if (total <= 0) {
empty++;
continue;
}
const shares = counts.map((v) => (v ?? 0) / total);
const neg = shares.slice(0, half).reduce((s, v) => s + v, 0);
const pos = shares.slice(k - half).reduce((s, v) => s + v, 0);
items.push({ name: String(r?.[label] ?? ""), counts, shares, total, net: pos - neg, row: r });
}
if (invalid) issues.push({ level: "error", message: `${invalid} answer value(s) are not numbers. Convert to numbers before charting.` });
if (negative) issues.push({ level: "note", message: `${negative} negative value(s) are not drawn; answers are counts or shares.` });
if (empty) issues.push({ level: "note", message: `${empty} row(s) without any answers are not drawn.` });
if (sort === "net") items = [...items].sort((a, b) => b.net - a.net);
return { items, issues };
}, [data, label, sig, sort]); // eslint-disable-line react-hooks/exhaustive-deps
const { items } = prep;
const height = hProp ?? Math.max(120, items.length * 34 + 34);
const legend: LegendItem[] = names.map((n, i) => ({ key: keys[i], label: n, color: tokens.div(stepOf(i, keys.length)), shape: "square" }));
const table = {
columns: [
{ key: "name", label },
...keys.map((k, i) => ({ key: `c${i}`, label: names[i], align: "right" as const, format: (v: unknown) => formatValue(v as number, undefined, { context: "table" }) })),
{ key: "net", label: netLabel, align: "right" as const, format: (v: unknown) => netText(v as number) },
],
rows: items.map((it) => ({ name: it.name, ...Object.fromEntries(it.counts.map((c, i) => [`c${i}`, c])), net: it.net })),
};
const summary = `Diverging stacked bars for ${items.length} item(s) on a ${keys.length}-point scale. ${items
.slice(0, 8)
.map((it) => `${it.name}: ${netLabel} ${netText(it.net)}`)
.join("; ")}.`;
return (
<ChartFrame {...frame} height={height} issues={prep.issues} table={table} summary={summary} legend={legend}>
{({ width }) => <Plot {...{ width, height, items, names, netLabel, showNet }} />}
</ChartFrame>
);
}
const netText = (net: number) => {
if (!Number.isFinite(net)) return "–";
const v = Math.round(net * 100);
return v > 0 ? `+${v}` : v < 0 ? `−${Math.abs(v)}` : "0";
};
function Plot(p: { width: number; height: number; items: Item[]; names: string[]; netLabel: string; showNet: boolean }) {
const { width, height, items, names } = p;
const k = names.length;
const half = Math.floor(k / 2);
const hasMid = k % 2 === 1;
const { active, setActive, keyProps } = useActiveIndex(items.length, { describe: (i) => ({ label: items[i]?.name, row: items[i]?.row }) });
const labelW = Math.min(width * 0.34, Math.max(...items.map((it) => textWidth(it.name, AXIS_FONT)), 20) + 14);
const netW = p.showNet ? Math.max(textWidth(p.netLabel, AXIS_FONT), 30) + 14 : 6;
const top = 18;
const bottom = height - 18;
const left = (it: Item) => it.shares.slice(0, half).reduce((s, v) => s + v, 0) + (hasMid ? it.shares[half] / 2 : 0);
const right = (it: Item) => it.shares.slice(k - half).reduce((s, v) => s + v, 0) + (hasMid ? it.shares[half] / 2 : 0);
const reach = Math.max(0.5, ...items.map(left), ...items.map(right));
const M = Math.min(1, Math.ceil(reach * 4) / 4);
const x = linearScale([-M, M], [labelW, width - netW]);
const step = M <= 0.75 ? 0.25 : 0.5;
const ticks: number[] = [];
for (let v = -M; v <= M + 1e-9; v += step) ticks.push(Math.round(v * 100) / 100);
const band = bandScale(items.length, [top, bottom], { paddingInner: 0.28, paddingOuter: 0.1 });
const onMove = (e: PointerEvent<SVGRectElement>) => setActive(band.indexAt(localPoint(e).y + top));
const segs = (it: Item) => {
const out: { i: number; x0: number; x1: number }[] = [];
let cur = -left(it);
for (let i = 0; i < k; i++) {
const w = it.shares[i];
out.push({ i, x0: cur, x1: cur + w });
cur += w;
}
return out;
};
const tip = (it: Item): TooltipRow[] => [
...names
.map((n, i) => ({ label: n, value: `${formatShare(it.shares[i], 0)}${it.counts[i] !== null ? ` (${formatValue(it.counts[i], undefined)})` : ""}`, color: tokens.div(stepOf(i, k)), shape: "square" as const }))
.reverse(),
{ label: p.netLabel, value: netText(it.net), strong: true },
];
return (
<>
<svg width={width} height={height} role="group" aria-roledescription="chart" aria-label="Diverging stacked bar chart. Use arrow keys to read rows." {...keyProps}>
{ticks.map((t, i) => (
<g key={i} aria-hidden>
<line x1={x(t)} x2={x(t)} y1={top - 4} y2={bottom} style={{ stroke: t === 0 ? "var(--clui-axis)" : "var(--clui-grid)" }} />
<text x={x(t)} y={bottom + 14} textAnchor="middle" className="clui-tick">
{formatShare(Math.abs(t), 0)}
</text>
</g>
))}
{p.showNet && (
<text x={width - 4} y={top - 6} textAnchor="end" className="clui-tick" aria-hidden>
{p.netLabel}
</text>
)}
{items.map((it, r) => {
const y = band(r);
const h = band.bandwidth;
return (
<g key={r} className={`clui-mark${active !== null && active !== r ? " clui-dim" : ""}`}>
<text x={labelW - 10} y={y + h / 2} dy="0.32em" textAnchor="end" className="clui-tick" style={{ fill: "var(--clui-ink)" }}>
{truncate(it.name, labelW - 12, AXIS_FONT)}
</text>
{segs(it).map((s) => {
const x0 = x(s.x0);
const w = x(s.x1) - x0;
if (w <= 0) return null;
const step = stepOf(s.i, k);
const txt = formatShare(it.shares[s.i], 0);
return (
<g key={s.i}>
<rect x={x0} y={y} width={w} height={h} style={{ fill: tokens.div(step), stroke: "var(--clui-surface)" }} strokeWidth={1} />
{w > textWidth(txt, FONT) + 6 && h >= 14 && (
<text x={x0 + w / 2} y={y + h / 2} dy="0.32em" textAnchor="middle" className="clui-label" style={{ fill: tokens.divInk(step), pointerEvents: "none" }}>
{txt}
</text>
)}
</g>
);
})}
{p.showNet && (
<text x={width - 4} y={y + h / 2} dy="0.32em" textAnchor="end" className="clui-label-strong" style={{ fill: toneText(toneOf(it.net)) }}>
{netText(it.net)}
</text>
)}
</g>
);
})}
<rect x={0} y={top} width={width} height={Math.max(0, bottom - top)} fill="transparent" onPointerMove={onMove} onPointerLeave={() => setActive(null)} />
</svg>
{active !== null && items[active] && (
<ChartTooltip x={x(0)} y={band(active) + band.bandwidth / 2} width={width} height={height} data={{ title: items[active].name, rows: tip(items[active]) }} />
)}
</>
);
}
Totals and their parts, with negatives stacked below zero.
Positive and negative changes either side of zero, coloured by business direction.
Many items on one scale, optionally against a comparison, with no zero required.