<!-- generated by scripts/gen-docs.mjs from docs/system/scatter-chart.md. Edit the source and rerun. -->
# ScatterChart

## Description
Plots two measures of many things at once, one dot each, so a person can see how one measure relates to the other across the whole set.

`import { ScatterChart } from "@/components/cobalt/ui/scatter-chart"`, source `registry/cobalt/ui/scatter-chart.tsx`, status `ready-with-gaps`.
Foundation: `hand-rolled`. Traps checked: `trap/loading-layout-shift`, `trap/color-only-status`, `trap/live-region-double`, `trap/reduced-motion-ignored`, `trap/motion-transition-all`, `trap/motion-layout-property`, `trap/numbers-shift`, `trap/tooltip-essential`, `trap/tooltip-interactive`, `trap/touch-hover-flash`, `trap/hover-unguarded` (n/a: no CSS hover reveals anything; the overlay follows the hover store), `trap/demo-on-timers` (n/a: every example holds fixed data), `trap/illustration-announced` (n/a: the dots are `aria-hidden` and the table carries the data), `trap/loop-offscreen` (n/a: nothing loops).

### Foundation
Not applicable: hand-rolled.

| Given by the foundation | Added by the team |
|---|---|
| The `Chart` frame from `registry/cobalt/ui/chart.tsx` (a box of fixed height, one measured size, the hover store, the tooltip, the keyboard, the empty, pending and failure states, the hidden summary and table, `ChartLegend`, `ChartGrid`, `ChartXAxis` and `ChartCanvas`), and `d3-scale` linear scales with `valueDomain`, `tickFormatter`, `seriesColor`, `pointGrid` and `tableRows` from `chart-math.ts` | The scatter itself: a point is kept only when both values are finite numbers, then sorted by x and y so the keyboard walks left to right; one linear scale on each axis with a zero line where the range crosses zero, the x axis starting on a label and ending at a finer step than it is labelled, so a narrow plot labelled every 10 ends at 25 when the dots stop at 23 instead of at 40; a dot of radius 3.5 at 75 percent opacity, 2 past 2,000 points; a group per dot coloured from `--chart-1` to `--chart-6` in order, with a legend that only names them; the pointer picks the nearest dot within 24 pixels through a grid, never a scan, and a pointer farther than that picks none; the tooltip titled by `name` or, with none, by the x value; a table of up to 200 rows with a Group column; past 5,000 points the dots are painted on a canvas with the same scales while the axes, the hover and the focus stay SVG |

## Examples
Fees against size for private funds, coloured by strategy.

Real uses, 0 call sites (`rg -n "<ScatterChart\b" app registry docs/system/examples --glob '!docs/system/examples/scatter-chart/*'`): the showcase chrome renders no ScatterChart of its own, and the examples folder does not count.

Uses inside the registry: none. `registry/cobalt/ui/scatter-chart.test.tsx` renders it for the tests.

### Example files
| File | Covers | Caption |
|---|---|---|
| `docs/system/examples/scatter-chart/default.tsx` | default | Fees against size for private funds, coloured by strategy |
| `docs/system/examples/scatter-chart/in-card.tsx` | composition:Card | A year's return against volatility for 6,000 funds, painted on a canvas in a card; hover and the keys still find each one |

Example: Fees against size for private funds, coloured by strategy (`docs/system/examples/scatter-chart/default.tsx`)

```tsx
import { ScatterChart } from "@/components/cobalt/ui/scatter-chart";

// Private funds: gross assets in dollars and the management fee in percent.
const funds = [
  ["Alder Growth", "Private equity", 2.4e9, 1.5], ["Birch Credit", "Credit", 8.1e8, 1.1], ["Cedar Real Estate", "Real estate", 1.2e9, 1.25],
  ["Dune Partners", "Private equity", 4.6e9, 1.2], ["Elm Opportunities", "Credit", 3.3e8, 1.4], ["Fern Property", "Real estate", 5.5e8, 1.6],
  ["Grove Ventures", "Private equity", 1.9e8, 2.0], ["Hazel Income", "Credit", 2.2e9, 0.9], ["Iris Logistics", "Real estate", 3.1e9, 1.0],
  ["Juniper Buyout", "Private equity", 6.8e9, 1.0], ["Kestrel Lending", "Credit", 1.4e9, 1.0], ["Larch Housing", "Real estate", 9.0e8, 1.35],
  ["Maple Secondaries", "Private equity", 1.1e9, 1.25], ["Nettle Mezzanine", "Credit", 6.0e8, 1.5], ["Oak Storage", "Real estate", 2.0e9, 1.1],
].map(([name, strategy, assets, fee]) => ({ name: String(name), strategy: String(strategy), assets: Number(assets), fee: Number(fee) }));

export default function Example() {
  return (
    <ScatterChart
      label="Fees against size"
      data={funds}
      x="assets"
      y="fee"
      name="name"
      group="strategy"
      xLabel="Gross assets"
      yLabel="Management fee"
      xFormat="money"
      yFormat="percent"
    />
  );
}
```

Example: A year's return against volatility for 6,000 funds, painted on a canvas in a card; hover and the keys still find each one (`docs/system/examples/scatter-chart/in-card.tsx`)

```tsx
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/cobalt/ui/card";
import { ScatterChart } from "@/components/cobalt/ui/scatter-chart";

// 6,000 funds from a seeded generator, so every load draws the same dots: more volatile funds
// return more on average, and spread wider.
let seed = 20261017;
const random = () => {
  seed = (seed * 1664525 + 1013904223) % 4294967296;
  return seed / 4294967296;
};
const strategies = ["Equity", "Credit", "Multi-asset"];
const funds = Array.from({ length: 6000 }, (_, i) => {
  const strategy = i % 3;
  const volatility = (strategy === 1 ? 2 : strategy === 2 ? 5 : 9) + random() * (strategy === 1 ? 8 : 14);
  const spread = (random() + random() + random() - 1.5) * volatility * 0.8;
  return {
    name: `Fund ${String(i + 1).padStart(4, "0")}`,
    strategy: strategies[strategy] ?? "",
    volatility: Math.round(volatility * 10) / 10,
    return: Math.round((1.5 + volatility * 0.45 + spread) * 10) / 10,
  };
});

export default function Example() {
  return (
    <Card className="w-full max-w-xl">
      <CardHeader>
        <CardTitle render={<h2 />}>Return against volatility</CardTitle>
        <CardDescription>6,000 funds, the year to September.</CardDescription>
      </CardHeader>
      <CardContent>
        <ScatterChart
          label="Return against volatility"
          height="lg"
          data={funds}
          x="volatility"
          y="return"
          name="name"
          group="strategy"
          xLabel="Volatility"
          yLabel="Return"
          xFormat="percent"
          yFormat="percent"
        />
      </CardContent>
    </Card>
  );
}
```

## Variants
Not applicable: ScatterChart has no variant axis of its own. It takes the frame's `height` steps, which Chart documents, and the switch to a canvas past 5,000 points is automatic, not a prop (see Limits).

## States
| State | Trigger | What the user can do | Shown by, besides color | Checked by |
|---|---|---|---|---|
| idle | at least one point with both values finite | read the dots, hover, tab in | the dots, the axes, the legend when `group` is passed | screenshot |
| hover | the pointer within 24 pixels of a dot, a finger within 36 | read the tooltip, move along | a 1px crosshair on both axes, a marker on the dot that keeps the dot's radius and adds a 2px ring of the card, the tooltip 6px above it with the name, the group and both values | screenshot |
| group hidden | a legend name pressed, with two groups or more | press it again to show the group | the name greyed with its swatch at 30%, `aria-pressed="false"`; the group's dots gone and out of the hover and the keys, the axes unchanged | test |
| focus | Tab reaches the box | step with the arrow keys | the system focus outline on the box, the last dot shown, the live line read aloud | by hand |
| canvas | more than 5,000 points | the same as idle | the dots on a canvas under the same axes; the marker, the crosshair and the tooltip stay SVG | screenshot |
| pending | `status="pending"` with nothing drawn yet | wait | `aria-busy`; nothing for 250ms, then a Skeleton block at the box's size | test |
| refreshing | `status="pending"` with marks on screen | read the old marks | `aria-busy`; after 250ms the marks dim to 55% and the hover stops; the new marks fade in when they arrive | by hand |
| empty | no point with both values finite, and not pending | read why | the sentence "Nothing to show for this period." centred in the box | test |
| failure | `status="failure"` | press Retry | the title "Could not load the chart" announced once as an alert, and Retry when `onRetry` is passed | test |

### State precedence
- Failure and pending: failure wins. The box shows the failure and its Retry.
- Pending and empty: pending wins. The box stays blank, then shows the Skeleton after the slow wait; the empty sentence never flashes.
- Pending and idle: both show. The old dots stay, dimmed to 55% once the slow wait passes, until the new data arrives.
- Hover and focus: the last one wins. The pointer and the keys move the same marker, so one dot shows at a time.
- Canvas and hover: both show. The canvas paints the dots and the SVG overlay draws the marker and the tooltip above them.

### Motion
| Trigger | Kind | Preset | Properties | Reduced motion |
|---|---|---|---|---|
| the crosshair, marker and tooltip appear or leave | announce | `popup-motion` at `--t-press` 140ms on `--curve`, leaving at 70% | opacity | the same fade, which the base layer keeps |
| the hovered dot changes | input | none: snaps with no transition | transform | the same snap |
| a legend name is hovered or focused, and the other groups dim | announce | `duration-press` on `--curve` | opacity | the same fade |

## Props

<!-- Props generated from registry/cobalt/ui/scatter-chart.tsx with TypeScript by scripts/props-table.mjs -->
| Prop | Type | Default | Purpose |
|---|---|---|---|
| `data` | `readonly T[]` |  |  |
| `label` | `string` |  |  |
| `x` | `Accessor<T, number>` |  |  |
| `y` | `Accessor<T, number>` |  |  |
| `active?` | `number` |  |  |
| `className?` | `string` |  |  |
| `group?` | `Accessor<T, string>` |  | A group per point, coloured in the series order with a legend. |
| `height?` | `ChartHeight` |  |  |
| `labels?` | `Partial<ChartLabels>` |  |  |
| `layers?` | `((scope: ChartScope) => ReactNode)` |  | Your own SVG over the dots, drawn with the chart's two value scales. |
| `locale?` | `string` |  |  |
| `name?` | `Accessor<T, string>` |  | What each point is, the tooltip's title: a fund's name. |
| `onActiveChange?` | `((index: number) => void)` |  |  |
| `onRetry?` | `(() => void)` |  |  |
| `status?` | `Status` |  |  |
| `summary?` | `string` |  | Your own sentence for screen readers; one is written from the data otherwise. |
| `tooltip?` | `boolean` |  |  |
| `xFormat?` | `ValueFormat` | `"number"` |  |
| `xLabel?` | `string` | `"x"` | What the two axes measure, for the tooltip and the table: "Assets", "Fees". |
| `yFormat?` | `ValueFormat` | `"number"` |  |
| `yLabel?` | `string` | `"y"` |  |

`data` is the rows, and `x` and `y` read a number from each, as a key or a function; a row without a finite number for both is left out. `name` reads what each dot is, the tooltip's title and the table's row header. `group` reads the group a dot belongs to, in the order the groups first appear. `xLabel` and `yLabel` name the two measures for the tooltip and the table, and `xFormat` and `yFormat` shape their values. `layers` draws your own SVG over the dots with the two value scales. With `group` the legend's line is there from the first render, so the chart does not move when the groups arrive, and with two groups or more each name is a button that hides and shows its dots, as on a line chart; the axes keep every dot, so the dots left keep their places, and a hidden group's dots leave the hover and the keys. The pointer picks a dot within 24 pixels and a finger within 36. The frame's props pass through: `label`, `summary`, `status`, `onRetry`, `height`, `labels`, `tooltip`, `active`, `onActiveChange` and `locale`; `active` and `onActiveChange` speak in the dot's row in `data`, though the dots are kept left to right. `SCATTER_CANVAS_FROM` is exported, 5,000.

## Usage

### When to use
- Two measures of many things at once, where the spread and the outliers are the point, such as fees against size across funds.
- Dots that fall in at most six groups a person can name.

### When not to use
- One measure over time. Use LineChart instead.
- Values by two names, shaded by size. Use Heatmap instead.
- Ranked names whose values are read one by one. Use BarList instead.

### Rules
- `rule/scatter-chart-name-the-dot`: When each point is a thing a person knows by name, pass `name` instead of leaving the tooltip titled by its x value, because the tooltip title, the table's row header and the live line all read `name`, and without it they read "Gross assets $2.4B" for a fund. Evidence: principle heuristic: recognition rather than recall, a fund is known by its name. Check: test `scatter-chart.test.tsx` expects the row headers "Birch" and "Alder".
  - Don't: `<ScatterChart label="Fees against size" data={funds} x="assets" y="fee" />`
  - Do: `<ScatterChart label="Fees against size" data={funds} x="assets" y="fee" name="name" />`
- `rule/scatter-chart-format-each-axis`: When an axis holds money or a percent, pass `xFormat` and `yFormat` instead of formatting the values in the data, because the format gives the ticks one unit, the tooltip and the table the same figures, and a pre-formatted string is not a number the scale can place. Evidence: principle heuristic: consistency and standards, one column of figures shares one unit. Check: test `scatter-chart.test.tsx` expects `<td>$810M</td><td>1.1%</td>`.
  - Don't: `<ScatterChart label="Fees" data={funds.map((f) => ({ ...f, assets: money(f.assets) }))} x="assets" y="fee" />`
  - Do: `<ScatterChart label="Fees" data={funds} x="assets" y="fee" xFormat="money" yFormat="percent" />`

### Content
- Follows `rule/writing-no-invented-numbers`.
- `rule/scatter-chart-axis-labels-name-the-measures`: When a chart is placed, pass `xLabel` and `yLabel` as the measures in words, such as "Gross assets" and "Management fee", instead of the defaults "x" and "y", because the tooltip rows, the table heads and the summary read them, and the default is a letter. Evidence: principle wcag: 1.1.1 Non-text content; principle wcag: 2.4.6 Headings and Labels. Check: review of every `ScatterChart` for `xLabel` and `yLabel`.
  - Don't: `<ScatterChart label="Fees against size" data={funds} x="assets" y="fee" />`
  - Do: `<ScatterChart label="Fees against size" data={funds} x="assets" y="fee" xLabel="Gross assets" yLabel="Management fee" />`

### Anti-slop
- `rule/scatter-chart-group-colours-in-order`: When dots fall in groups, pass `group` and let the chart take `--chart-1` to `--chart-6` in order instead of a colour per dot, because the order keeps neighbours apart for colour-blind readers and the legend names each colour once. Evidence: measured adjacent CVD delta E 14.6 light and 10.8 dark with the validator, docs/system/colors.md; person D13. Check: test `chart-math.test.ts` expects `seriesColor(0)` to be `--chart-1` and `seriesColor(5)` `--chart-6`.
  - Don't: `<ScatterChart data={funds.map((f) => ({ ...f, fill: "oklch(0.6 0.2 140)" }))} x="assets" y="fee" label="Fees" />`
  - Do: `<ScatterChart data={funds} x="assets" y="fee" group="strategy" label="Fees" />`

### Limits
- `rule/scatter-chart-six-groups`: When dots would fall in more than 6 groups, fold the smallest into an "Other" group or split the chart, because the 7th group takes the colour of the 1st at 30 percent strength, the only cue a dot can carry, and two faint dots of one hue are hard to tell apart. Evidence: measured 12 groups drawn in 6 colours, the second six at 30 percent, .design-system/tmp/charts/scatter-chart-worst-1440-light.png; measured the 7th slot resolves to `--chart-1`, registry/cobalt/lib/chart-math.test.ts. Check: review of every `group` that can return more than six names.
  - Don't: `<ScatterChart data={funds} x="assets" y="fee" group="manager" label="Fees" />`
  - Do: `<ScatterChart data={funds} x="assets" y="fee" group={(f) => (topFive.has(f.manager) ? f.manager : "Other")} label="Fees" />`
- `rule/scatter-chart-canvas-past-5000`: When a scatter chart holds more than 5,000 points, let it paint them on its canvas, which it does by itself, instead of forcing SVG dots, because one SVG node per dot costs 6.7ms to build at 5,000 and 30.6ms at 20,000, the second past a 16.7ms frame, against 1.0ms and 1.9ms on a canvas in one run. Evidence: measured 6.7ms for 5,000 SVG circles and 30.6ms for 20,000 against 1.0ms and 1.9ms on canvas, docs/research/2026-10-17-charts.md; measured hover median 3ms and layout shift 0 on 100,000 points on the canvas, .design-system/evidence/charts/hover-cost.jsonl. Check: test `scatter-chart.test.tsx` expects the 5,000 threshold.
  - Don't: `points.map((p) => <circle cx={p.x} cy={p.y} r={3.5} />)`
  - Do: `<ScatterChart label="Fees against size" data={points} x="assets" y="fee" />`

## Accessibility
Rests on the Chart frame: a focusable `div` with `role="group"` and `aria-roledescription="chart"`, one tab stop per chart. The dots are `aria-hidden`; the data is a visually hidden sentence ("Fees against size: 15 points. Gross assets from $190M to $6.8B.") through `aria-describedby` and a visually hidden `table` with a Group column, sampled to 200 evenly spaced rows with a note past that. On the picture, a group is told apart by colour only; the tooltip, the live line and the table name it in text. Series colours hold 3:1 on the card in both themes (`chart-math.test.ts`). Screen reader pass with VoiceOver: NEEDS REVIEW.

### Keyboard
| Key | Where focus is | Effect | Focus after | Checked by |
|---|---|---|---|---|
| Tab | before the chart | focuses the box and shows the last dot, the one with the greatest x | the box | by hand |
| Right, Left | the box | the next or previous dot in order of x | the box | by hand |
| Down, Up | the box | nothing: the dots are one sequence, left to right | the box | by hand |
| Home, End | the box | the first or the last dot | the box | by hand |
| Page Down, Page Up | the box | a tenth of the dots on or back, at least 2 | the box | by hand |
| Escape | the box, or the pointer over it | hides the crosshair and tooltip | stays | by hand |
| Tab | the box | leaves the chart; with two groups or more the legend buttons come next | the next control | by hand |

### ARIA
| Part | Role | Accessible name from | States and properties | Announced | Checked by |
|---|---|---|---|---|---|
| box | group | `label`, through `aria-label`; `aria-roledescription` from `labels.chart` | `aria-describedby` the summary; `aria-busy` while pending | the name, "chart" and the summary when it is reached | test |
| live line | none, `aria-live="polite"` | nothing | none | the name, the group, then each measure and its value as the keys move; pointer moves are silent | by hand |
| table | table | its caption, the `label` | a row header per dot | read on request from the table list | test |
| legend item | button, with two groups or more | its group name | `aria-pressed` | the name and pressed or not | test |
| failure | alert | its title | none | "Could not load the chart" once | test |

## Tokens
| Part | State | Token |
|---|---|---|
| dots | all | `--chart-1`, `--chart-2`, `--chart-3`, `--chart-4`, `--chart-5`, `--chart-6` |
| gridlines | all | `--chart-grid` |
| zero line | all | `--border` |
| axis labels | all | `--muted-foreground` |
| crosshair | hover | `--foreground` at 15% |
| marker ring | hover | `--card` |
| tooltip | hover | `--tip`, `--tip-foreground`, `--r-md`, `--t-press`, `--curve` |
| legend swatch | all | `--r-xs` |

## Related
- Chart: the frame every chart draws in, and its hover, keyboard and states.
- Heatmap: values by two names, shaded by size.
- LineChart: one measure over time.
- BarList: ranked names whose values are read one by one.
- Histogram: how many rows fall into each range of a value.
