Dumbbell chart
Before and after per item with the change printed and coloured by direction.
Two points in time per item, where both change and rank matter.
<SlopeChart />Slope chart is free under the MIT license.
$ npx shadcn@latest add https://chartslibraryui.com/r/slope-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 { SlopeChart } from "@/components/charts/slope-chart";
import { marketShare } from "./sample-data";
export function Example() {
return (
<SlopeChart
title="We gained 4.5 points of share in two years"
subtitle="Share of category revenue"
data={marketShare}
label="vendor"
from="y2024"
to="y2026"
fromLabel="2024"
toLabel="2026"
format={{ kind: "percent", decimals: 1 }}
/>
);
}
Rows with a label key and two numeric keys (from, to).
[{ vendor: "Ours", y2024: 0.142, y2026: 0.187 }, ...]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 SlopeChartProps extends FrameProps {
data: Row[];
/** Key of the item name. */
label: string;
/** Key of the start value. */
from: string;
/** Key of the end value. */
to: string;
fromLabel?: string;
toLabel?: string;
format?: FormatInput;
/** Items to emphasise; the rest are grey. Default: colour by direction of change. */
highlight?: string[];
favorable?: Favorable;
/** Include zero. Default false (slopes show change in rank and level). */
zero?: boolean;
}Installs slope-chart.tsx and the shared core/ (11 files).
"use client";
import { useMemo } from "react";
import { AXIS_FONT, placeEndLabels } from "./core/axis";
import { color as tokens, toneOf, toneColor, type Favorable } from "./core/color";
import { readNum, type Issue, type Row } from "./core/data";
import { formatDelta, formatValue, type FormatInput } from "./core/format";
import { ChartFrame, ChartTooltip, useActiveIndex, type FrameProps } from "./core/frame";
import { linearScale, valueDomain } from "./core/scale";
import { textWidth, truncate } from "./core/text";
export interface SlopeChartProps extends FrameProps {
data: Row[];
/** Key of the item name. */
label: string;
/** Key of the start value. */
from: string;
/** Key of the end value. */
to: string;
fromLabel?: string;
toLabel?: string;
format?: FormatInput;
/** Items to emphasise; the rest are grey. Default: colour by direction of change. */
highlight?: string[];
favorable?: Favorable;
/** Include zero. Default false (slopes show change in rank and level). */
zero?: boolean;
}
/**
* Two points in time per item, where both the change and the ranking matter. Works up to about 10 items;
* beyond that, use a dot plot with a comparison.
*/
export function SlopeChart({
data,
label,
from,
to,
fromLabel = from,
toLabel = to,
format,
highlight,
favorable = "up",
zero = false,
height = 320,
...frame
}: SlopeChartProps) {
const { items, issues } = useMemo(() => {
const issues: Issue[] = [];
if (!Array.isArray(data) || !data.length) return { items: [] as { name: string; a: number; b: number }[], issues: [{ level: "error", message: "No data to display." }] as Issue[] };
const items: { name: string; a: number; b: number }[] = [];
let incomplete = 0;
for (const row of data) {
const a = readNum(row?.[from]);
const b = readNum(row?.[to]);
if (a.state === "invalid" || b.state === "invalid") issues.push({ level: "error", message: `"${row?.[label]}" has a non-numeric value.` });
else if (a.value === null || b.value === null) incomplete++;
else items.push({ name: String(row?.[label] ?? ""), a: a.value, b: b.value });
}
if (incomplete) issues.push({ level: items.length ? "note" : "error", message: items.length ? `${incomplete} item(s) missing a start or end value are not drawn.` : "Every item is missing a start or end value, so there is nothing to draw." });
if (items.length > 12) issues.push({ level: "warning", message: `${items.length} items make a slope chart hard to read. Consider a dot plot.` });
return { items, issues };
}, [data, label, from, to]);
const table = {
columns: [
{ key: "name", label },
{ key: "a", label: fromLabel, align: "right" as const, format: (v: unknown) => formatValue(v as number, format, { context: "table" }) },
{ key: "b", label: toLabel, align: "right" as const, format: (v: unknown) => formatValue(v as number, format, { context: "table" }) },
{ key: "d", label: "Change", align: "right" as const, format: (v: unknown) => formatDelta(v as number, format, "table") },
],
rows: items.map((d) => ({ name: d.name, a: d.a, b: d.b, d: d.b - d.a })),
};
const summary = `Slope chart of ${items.length} items from ${fromLabel} to ${toLabel}. ${items
.slice(0, 6)
.map((d) => `${d.name}: ${formatValue(d.a, format)} to ${formatValue(d.b, format)}`)
.join("; ")}.`;
return (
<ChartFrame {...frame} height={height} issues={issues} table={table} summary={summary}>
{({ width }) => <SlopeInner {...{ width, height, items, format, highlight, favorable, zero, fromLabel, toLabel }} />}
</ChartFrame>
);
}
function SlopeInner(p: {
width: number;
height: number;
items: { name: string; a: number; b: number }[];
format?: FormatInput;
highlight?: string[];
favorable: Favorable;
zero: boolean;
fromLabel: string;
toLabel: string;
}) {
const { width, height, items } = p;
const { active, setActive, keyProps } = useActiveIndex(items.length);
const top = 28;
const bottom = height - 10;
const { domain } = valueDomain(items.flatMap((d) => [d.a, d.b]), { includeZero: p.zero, ticks: 4 });
const sy = linearScale(domain, [bottom, top]);
const labelText = (d: { name: string }, v: number) => `${formatValue(v, p.format)} ${d.name}`;
const maxLabel = Math.min(width * 0.32, Math.max(...items.map((d) => textWidth(labelText(d, Math.max(d.a, d.b)), AXIS_FONT))) + 8);
const x0 = maxLabel + 8;
const x1 = width - maxLabel - 8;
const hl = p.highlight ? new Set(p.highlight) : null;
const colorOf = (d: { name: string; a: number; b: number }) =>
hl ? (hl.has(d.name) ? tokens.series(0) : tokens.context) : toneColor(toneOf(d.b - d.a, p.favorable));
const leftYs = placeEndLabels(items.map((d) => sy(d.a)), 13, top, bottom, 60);
const rightYs = placeEndLabels(items.map((d) => sy(d.b)), 13, top, bottom, 60);
const showLabel = (d: { name: string }) => !hl || hl.has(d.name) || (leftYs !== null && rightYs !== null);
return (
<>
<svg width={width} height={height} role="group" aria-roledescription="chart" aria-label="Slope chart. Use arrow keys to read items." {...keyProps}>
<line x1={x0} x2={x0} y1={top - 6} y2={bottom} style={{ stroke: "var(--clui-axis)" }} />
<line x1={x1} x2={x1} y1={top - 6} y2={bottom} style={{ stroke: "var(--clui-axis)" }} />
<text x={x0} y={12} textAnchor="middle" className="clui-label-strong">
{p.fromLabel}
</text>
<text x={x1} y={12} textAnchor="middle" className="clui-label-strong">
{p.toLabel}
</text>
{items.map((d, i) => {
const c = colorOf(d);
const dim = active !== null && active !== i;
const ly = leftYs?.[i] ?? sy(d.a);
const ry = rightYs?.[i] ?? sy(d.b);
return (
<g key={d.name + i} className={`clui-mark${dim ? " clui-dim" : ""}`} onPointerEnter={() => setActive(i)} onPointerLeave={() => setActive(null)}>
<line x1={x0} x2={x1} y1={sy(d.a)} y2={sy(d.b)} style={{ stroke: c }} strokeWidth={hl && !hl.has(d.name) ? 1.5 : 2} strokeLinecap="round" />
<circle cx={x0} cy={sy(d.a)} r={4} style={{ fill: c, stroke: "var(--clui-surface)" }} strokeWidth={1.5} />
<circle cx={x1} cy={sy(d.b)} r={4} style={{ fill: c, stroke: "var(--clui-surface)" }} strokeWidth={1.5} />
{showLabel(d) && (
<>
<text x={x0 - 10} y={ly} dy="0.32em" textAnchor="end" className="clui-label">
{truncate(labelText(d, d.a), maxLabel, AXIS_FONT)}
</text>
<text x={x1 + 10} y={ry} dy="0.32em" className="clui-label">
{truncate(`${formatValue(d.b, p.format)} ${d.name}`, maxLabel, AXIS_FONT)}
</text>
</>
)}
<line x1={x0} x2={x1} y1={sy(d.a)} y2={sy(d.b)} stroke="transparent" strokeWidth={14} />
</g>
);
})}
</svg>
{active !== null && items[active] && (
<ChartTooltip
x={(x0 + x1) / 2}
y={(sy(items[active].a) + sy(items[active].b)) / 2}
width={width}
height={height}
data={{
title: items[active].name,
rows: [
{ label: p.fromLabel, value: formatValue(items[active].a, p.format, { context: "tooltip" }) },
{ label: p.toLabel, value: formatValue(items[active].b, p.format, { context: "tooltip" }) },
{ label: "Change", value: formatDelta(items[active].b - items[active].a, p.format, "tooltip"), strong: true },
],
}}
/>
)}
</>
);
}
Before and after per item with the change printed and coloured by direction.
Many items on one scale, optionally against a comparison, with no zero required.
Trends over time for one to four series, with gaps for missing data and marked forecasts.