Histogram
The shape of one distribution, with automatic binning and a median marker.
The relationship between two measures, with groups, bubbles, quadrants and a trend line.
<ScatterChart />Scatter chart is free under the MIT license.
$ npx shadcn@latest add https://chartslibraryui.com/r/scatter-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 { ScatterChart } from "@/components/charts/scatter-chart";
import { accounts } from "./sample-data";
export function Example() {
return (
<ScatterChart
title="ARR scales with seats, at a discount for enterprise"
subtitle="Accounts by seats and annual recurring revenue"
data={accounts}
x="seats"
y="arr"
group="segment"
name="account"
xLabel="Seats"
yLabel="ARR"
xFormat="integer"
yFormat="currency"
trend
/>
);
}
Rows with two numeric keys; optional size, group and name keys.
[{ account: "Acme", seats: 240, arr: 98000, segment: "Mid-market" }, ...]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 ScatterChartProps extends FrameProps {
data: Row[];
x: string;
y: string;
/** Optional bubble size key (area is proportional to the value). */
size?: string;
/** Optional group key; up to 3 groups get distinct colours. */
group?: string;
/** Key used to name points in tooltips and labels. */
name?: string;
xLabel?: string;
yLabel?: string;
xFormat?: FormatInput;
yFormat?: FormatInput;
sizeFormat?: FormatInput;
/** Names of points to label directly. */
labelPoints?: string[];
/** Reference lines splitting the plot into quadrants. */
xRef?: number;
yRef?: number;
/** Least-squares trend line. */
trend?: boolean;
/** Include zero on the axes. Default false: position encodes value, so zero isn't required. */
zero?: boolean;
/** Point names to emphasise; others are grey. */
highlight?: string[];
}Installs scatter-chart.tsx and the shared core/ (11 files).
"use client";
import { useMemo, type PointerEvent } from "react";
import { AXIS_FONT, XGrid, YGrid, axisWidth } from "./core/axis";
import { color as tokens } from "./core/color";
import { readNum, type Issue, type Row } from "./core/data";
import { formatValue, tickFormatter, type FormatInput } from "./core/format";
import { ChartFrame, ChartTooltip, localPoint, useActiveIndex, type FrameProps, type LegendItem } from "./core/frame";
import { linearScale, valueDomain } from "./core/scale";
import { textWidth } from "./core/text";
export interface ScatterChartProps extends FrameProps {
data: Row[];
x: string;
y: string;
/** Optional bubble size key (area is proportional to the value). */
size?: string;
/** Optional group key; up to 3 groups get distinct colours. */
group?: string;
/** Key used to name points in tooltips and labels. */
name?: string;
xLabel?: string;
yLabel?: string;
xFormat?: FormatInput;
yFormat?: FormatInput;
sizeFormat?: FormatInput;
/** Names of points to label directly. */
labelPoints?: string[];
/** Reference lines splitting the plot into quadrants. */
xRef?: number;
yRef?: number;
/** Least-squares trend line. */
trend?: boolean;
/** Include zero on the axes. Default false: position encodes value, so zero isn't required. */
zero?: boolean;
/** Point names to emphasise; others are grey. */
highlight?: string[];
}
interface Pt {
i: number;
x: number;
y: number;
s: number | null;
g: string;
n: string;
}
/**
* The relationship between two measures, one point per item. Outliers are always drawn; nothing is clipped.
* With more than about 2,000 points, consider a heatmap or hexbin instead.
*/
export function ScatterChart({
data,
x,
y,
size,
group,
name,
xLabel,
yLabel,
xFormat,
yFormat,
sizeFormat,
labelPoints = [],
xRef,
yRef,
trend = false,
zero = false,
highlight,
height = 320,
...frame
}: ScatterChartProps) {
const { points, issues, groups } = useMemo(() => {
const issues: Issue[] = [];
if (!Array.isArray(data) || !data.length)
return { points: [] as Pt[], issues: [{ level: "error", message: "No data to display." }] as Issue[], groups: [] as string[] };
const points: Pt[] = [];
let missing = 0;
let invalid = 0;
let negSize = 0;
data.forEach((row, i) => {
const rx = readNum(row?.[x]);
const ry = readNum(row?.[y]);
const rs = size ? readNum(row?.[size]) : null;
if (rx.state === "invalid" || ry.state === "invalid" || rs?.state === "invalid") return void invalid++;
if (rx.value === null || ry.value === null) return void missing++;
if (rs && rs.value !== null && rs.value < 0) return void negSize++;
points.push({
i,
x: rx.value,
y: ry.value,
s: rs?.value ?? null,
g: group ? String(row?.[group] ?? "") : "",
n: name ? String(row?.[name] ?? `#${i + 1}`) : `#${i + 1}`,
});
});
if (invalid) issues.push({ level: "error", message: `${invalid} row(s) have non-numeric x, y or size values.` });
if (negSize) issues.push({ level: "error", message: `${negSize} row(s) have a negative bubble size; area can't be negative.` });
if (missing) issues.push({ level: "note", message: `${missing} row(s) without both x and y are not drawn.` });
if (!points.length && !invalid) issues.push({ level: "error", message: "No complete (x, y) pairs to draw." });
const groups = group ? [...new Set(points.map((p) => p.g))] : [];
if (groups.length > 3)
issues.push({
level: "warning",
message: `${groups.length} groups: colours beyond three are hard to tell apart in a scatter. Consider small multiples.`,
});
return { points, issues, groups };
}, [data, x, y, size, group, name]);
const colorOf = (g: string) => (group ? (groups.indexOf(g) < 8 ? tokens.series(groups.indexOf(g)) : tokens.context) : tokens.series(0));
const legend: LegendItem[] = groups.map((g) => ({ key: g, label: g, color: colorOf(g), shape: "dot" }));
const table = {
columns: [
{ key: "n", label: name ?? "Point" },
...(group ? [{ key: "g", label: group }] : []),
{ key: "x", label: xLabel ?? x, align: "right" as const, format: (v: unknown) => formatValue(v as number, xFormat, { context: "table" }) },
{ key: "y", label: yLabel ?? y, align: "right" as const, format: (v: unknown) => formatValue(v as number, yFormat, { context: "table" }) },
...(size ? [{ key: "s", label: size, align: "right" as const, format: (v: unknown) => formatValue(v as number, sizeFormat, { context: "table" }) }] : []),
],
rows: points.map((p) => ({ n: p.n, g: p.g, x: p.x, y: p.y, s: p.s })),
};
const fit = trend ? linearFit(points) : null;
const summary = `Scatter plot of ${points.length} points, ${yLabel ?? y} against ${xLabel ?? x}.${
fit ? ` Trend: correlation ${fit.r.toFixed(2)}.` : ""
} Use arrow keys to step through points.`;
return (
<ChartFrame {...frame} height={height} issues={issues} table={table} summary={summary} legend={legend}>
{({ width }) => (
<ScatterPlot
{...{ width, height, points, colorOf, xFormat, yFormat, sizeFormat, labelPoints, xRef, yRef, zero, fit, xLabel: xLabel ?? x, yLabel: yLabel ?? y, size, highlight }}
/>
)}
</ChartFrame>
);
}
export function linearFit(points: { x: number; y: number }[]) {
const n = points.length;
if (n < 3) return null;
let sx = 0, sy = 0, sxx = 0, sxy = 0, syy = 0;
for (const p of points) {
sx += p.x;
sy += p.y;
sxx += p.x * p.x;
sxy += p.x * p.y;
syy += p.y * p.y;
}
const den = n * sxx - sx * sx;
if (den === 0) return null;
const slope = (n * sxy - sx * sy) / den;
const intercept = (sy - slope * sx) / n;
const r = (n * sxy - sx * sy) / Math.sqrt(den * (n * syy - sy * sy) || 1);
return { slope, intercept, r };
}
function ScatterPlot(p: {
width: number;
height: number;
points: Pt[];
colorOf: (g: string) => string;
xFormat?: FormatInput;
yFormat?: FormatInput;
sizeFormat?: FormatInput;
labelPoints: string[];
xRef?: number;
yRef?: number;
zero: boolean;
fit: { slope: number; intercept: number } | null;
xLabel: string;
yLabel: string;
size?: string;
highlight?: string[];
}) {
const { width, height, points } = p;
// keyboard order: left to right
const order = useMemo(() => points.map((pt, k) => ({ k, x: pt.x })).sort((a, b) => a.x - b.x).map((d) => d.k), [points]);
const { active, setActive, keyProps } = useActiveIndex(points.length);
const activePt = active !== null ? points[order[active]] : null;
const yd = valueDomain(points.map((d) => d.y).concat(p.yRef ?? []), { includeZero: p.zero, ticks: Math.max(3, Math.floor(height / 60)) });
const fy = tickFormatter(p.yFormat, yd.ticks);
const left = Math.max(axisWidth(yd.ticks.map(fy)), 8);
const right = width - 12;
const top = 18;
const bottom = height - 38;
const xd = valueDomain(points.map((d) => d.x).concat(p.xRef ?? []), { includeZero: p.zero, ticks: Math.max(3, Math.floor((right - left) / 90)) });
const fx = tickFormatter(p.xFormat, xd.ticks);
const sx = linearScale(xd.domain, [left, right]);
const sy = linearScale(yd.domain, [bottom, top]);
const maxS = Math.max(0, ...points.map((d) => d.s ?? 0));
const dense = points.length > 400;
const radius = (d: Pt) => (p.size && d.s !== null && maxS > 0 ? 3 + Math.sqrt(d.s / maxS) * 18 : dense ? 2.5 : 4);
const hl = p.highlight ? new Set(p.highlight) : null;
const onMove = (e: PointerEvent<SVGRectElement>) => {
const { x: mx, y: my } = localPoint(e);
let best = -1;
let bd = Infinity;
points.forEach((d, k) => {
const dx = sx(d.x) - (mx + left);
const dy = sy(d.y) - (my + top);
const dist = dx * dx + dy * dy;
if (dist < bd) {
bd = dist;
best = k;
}
});
setActive(bd < 40 * 40 && best >= 0 ? order.indexOf(best) : null);
};
return (
<>
<svg width={width} height={height} role="group" aria-roledescription="chart" aria-label="Scatter plot. Use arrow keys to step through points." {...keyProps}>
<YGrid ticks={yd.ticks} y={sy} x0={left} x1={right} format={fy} />
<XGrid ticks={xd.ticks} x={sx} y0={top} y1={bottom} format={fx} />
<text x={left} y={10} className="clui-annot" aria-hidden>
{p.yLabel} ↑
</text>
<text x={right} y={height - 4} textAnchor="end" className="clui-annot" aria-hidden>
{p.xLabel} →
</text>
{p.xRef !== undefined && (
<line x1={sx(p.xRef)} x2={sx(p.xRef)} y1={top} y2={bottom} style={{ stroke: "var(--clui-ink-2)" }} strokeDasharray="4 3" />
)}
{p.yRef !== undefined && (
<line x1={left} x2={right} y1={sy(p.yRef)} y2={sy(p.yRef)} style={{ stroke: "var(--clui-ink-2)" }} strokeDasharray="4 3" />
)}
{p.fit && (
<line
x1={sx(xd.domain[0])}
x2={sx(xd.domain[1])}
y1={sy(p.fit.intercept + p.fit.slope * xd.domain[0])}
y2={sy(p.fit.intercept + p.fit.slope * xd.domain[1])}
style={{ stroke: "var(--clui-ink-2)" }}
strokeWidth={1.25}
clipPath="none"
/>
)}
<g>
{[...points]
.sort((a, b) => (b.s ?? 0) - (a.s ?? 0))
.map((d) => {
const c = hl ? (hl.has(d.n) ? p.colorOf(d.g) : tokens.context) : p.colorOf(d.g);
return (
<circle
key={d.i}
cx={sx(d.x)}
cy={sy(d.y)}
r={radius(d)}
style={{ fill: c, stroke: "var(--clui-surface)", fillOpacity: p.size ? 0.7 : dense ? 0.6 : 0.9 }}
strokeWidth={dense ? 0.5 : 1.5}
/>
);
})}
</g>
{points
.filter((d) => p.labelPoints.includes(d.n))
.map((d) => {
const lx = sx(d.x) + radius(d) + 4;
const flip = lx + textWidth(d.n, AXIS_FONT) > right;
return (
<text key={`l${d.i}`} x={flip ? sx(d.x) - radius(d) - 4 : lx} y={sy(d.y)} dy="0.32em" textAnchor={flip ? "end" : "start"} className="clui-label clui-halo">
{d.n}
</text>
);
})}
{activePt && (
<circle cx={sx(activePt.x)} cy={sy(activePt.y)} r={radius(activePt) + 3} fill="none" style={{ stroke: "var(--clui-ink)" }} strokeWidth={1.5} />
)}
<rect x={left} y={top} width={Math.max(0, right - left)} height={Math.max(0, bottom - top)} fill="transparent" onPointerMove={onMove} onPointerLeave={() => setActive(null)} />
</svg>
{activePt && (
<ChartTooltip
x={sx(activePt.x)}
y={sy(activePt.y)}
width={width}
height={height}
data={{
title: activePt.n,
rows: [
...(activePt.g ? [{ label: "Group", value: activePt.g, color: p.colorOf(activePt.g), shape: "dot" as const }] : []),
{ label: p.xLabel, value: formatValue(activePt.x, p.xFormat, { context: "tooltip" }) },
{ label: p.yLabel, value: formatValue(activePt.y, p.yFormat, { context: "tooltip" }) },
...(p.size && activePt.s !== null ? [{ label: p.size, value: formatValue(activePt.s, p.sizeFormat, { context: "tooltip" }) }] : []),
],
}}
/>
)}
</>
);
}
The shape of one distribution, with automatic binning and a median marker.
Every observation visible by group, with the median marked.
Median, quartiles, whiskers and every outlier per group, with n printed.