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

## Description
Counts how many rows fall into each range of one value, so a person reads the shape of a distribution and the range where most rows lie.

`import { Histogram } from "@/components/cobalt/ui/histogram"`, source `registry/cobalt/ui/histogram.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 marks 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 |
|---|---|
| `d3-array` `bin` and the `d3-scale` linear scale with its nice ticks, for the maths only | The chart type on the shared Chart frame (fixed box, hover store, tooltip, keyboard, states, summary and table): bins on round edges that sit edge to edge on a value axis, a count axis with whole-number ticks only, rows with no value left out, a tooltip titled with the range and one row for the count, the bin under the pointer kept while the rest dim to 40%, and a written sentence that names the range with the most rows; the unit's plural forms (`unit`) put "funds" in the sentence, the tooltip and the table head |

## Examples
How many days after the quarter's end each adviser filed its 13F, against the 45-day deadline drawn in `layers`.

Real uses, 0 call sites (`rg -n "<Histogram\b" app docs/system/examples --glob '!docs/system/examples/histogram/*'`): no showcase page draws one outside its examples yet, and the examples folder does not count.

Uses inside the registry: none beyond its tests. The `ChartCard` example in-grid.tsx holds one beside a card of text.

### Example files
| File | Covers | Caption |
|---|---|---|
| `docs/system/examples/histogram/default.tsx` | default | How many days after the quarter's end each adviser filed its 13F, against the 45-day deadline drawn in `layers` |
| `docs/system/examples/histogram/in-card.tsx` | composition:ChartCard | Management fees across an adviser's 120 private funds in a chart card, with the median, read from the same rows, as the headline |

Example: How many days after the quarter's end each adviser filed its 13F, against the 45-day deadline drawn in `layers` (`docs/system/examples/histogram/default.tsx`)

```tsx
import { ChartReferenceLine } from "@/components/cobalt/ui/chart";
import { Histogram } from "@/components/cobalt/ui/histogram";

// Days from the end of June to each of 240 advisers' 13F filing, as [days, advisers].
const filed = [
  [12, 2], [18, 4], [22, 6], [26, 9], [29, 12], [31, 15], [33, 18], [35, 21], [37, 24],
  [39, 27], [41, 31], [43, 36], [44, 22], [47, 6], [52, 4], [58, 2], [66, 1],
].flatMap(([days, advisers]) => Array.from({ length: advisers ?? 0 }, () => ({ days: days ?? 0 })));

export default function Example() {
  return (
    <Histogram
      label="Days to file"
      data={filed}
      value="days"
      format={(days) => `${days}d`}
      unit={{ one: "adviser", other: "advisers" }}
      layers={(scope) => <ChartReferenceLine scope={scope} x={45} label="Deadline, day 45" />}
    />
  );
}
```

Example: Management fees across an adviser's 120 private funds in a chart card, with the median, read from the same rows, as the headline (`docs/system/examples/histogram/in-card.tsx`)

```tsx
import { ChartCard } from "@/components/cobalt/ui/chart-card";
import { Histogram } from "@/components/cobalt/ui/histogram";

// The management fee of each of 120 private funds, in percent, as [fee, funds].
const fees = [
  [0.5, 3], [0.65, 4], [0.75, 9], [0.85, 7], [1.0, 22], [1.1, 9], [1.25, 18], [1.35, 6],
  [1.5, 24], [1.65, 4], [1.75, 6], [2.0, 8],
].flatMap(([fee, funds]) => Array.from({ length: funds ?? 0 }, () => ({ fee: fee ?? 0 })));

const sorted = fees.map((f) => f.fee).sort((a, b) => a - b);
const median = ((sorted[59] ?? 0) + (sorted[60] ?? 0)) / 2;

export default function Example() {
  return (
    <ChartCard
      className="w-full max-w-xl"
      title="Management fee"
      value={`${median}%`}
      note={`Median of ${fees.length} funds, latest filings`}
    >
      <Histogram label="Funds by management fee" height="sm" data={fees} value="fee" format="percent" unit={{ one: "fund", other: "funds" }} />
    </ChartCard>
  );
}
```

## Variants
Not applicable: Histogram has no variant axis. Its look is fixed, bins edge to edge in the first series colour, counted in whole rows; `bins`, `format` and `unit` set the ranges, the edge words and the unit.

## States
| State | Trigger | What the user can do | Shown by, besides color | Checked by |
|---|---|---|---|---|
| idle | data with at least one value that is not zero | read the bins, hover, tab in | the bins, the axes, the count axis in whole rows | screenshot |
| hover | the pointer over the box, snapped to the nearest point or group | read the tooltip, move along | the tooltip 6px above the plot, centred on the bin, so it never covers a taller bin beside it, and the other bins dim to 40% | screenshot |
| focus | Tab reaches the box | step with the arrow keys | the system focus outline on the box, the last point shown, the live line read aloud | by hand |
| 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 value, or every value zero, 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.
- Hover and focus: the last one wins. The pointer and the keys move the same marker, so one point shows at a time.
- Missing values and empty: empty wins when no row has a value. Rows with no value are left out of every bin, and with none left the box shows the empty sentence.

### Motion
| Trigger | Kind | Preset | Properties | Reduced motion |
|---|---|---|---|---|
| the crosshair, markers 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 point changes | input | none: snaps with no transition | transform | the same snap |
| a bin dims beside the hovered one | announce | `duration-press` on `--curve` | opacity | the same fade |

## Props

<!-- Props generated from registry/cobalt/ui/histogram.tsx with TypeScript by scripts/props-table.mjs -->
| Prop | Type | Default | Purpose |
|---|---|---|---|
| `data` | `readonly T[]` |  |  |
| `label` | `string` |  |  |
| `value` | `Accessor<T, number>` |  | The value of a row that is counted into a bin. |
| `active?` | `number` |  |  |
| `bins?` | `number` | `12` | About how many bins: the edges land on round numbers, so the count is close, not exact. |
| `className?` | `string` |  |  |
| `format?` | `ValueFormat` | `"number"` | How the bin edges read. |
| `height?` | `ChartHeight` |  |  |
| `labels?` | `Partial<ChartLabels>` |  |  |
| `layers?` | `((scope: ChartScope) => ReactNode)` |  | Your own SVG over the bins, drawn with the chart's scales: `x` reads values, `y` counts. |
| `locale?` | `string` |  |  |
| `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` |  |  |
| `unit?` | `PluralForms` | `ITEMS` | What one counted row is, in each plural form: { one: "fund", other: "funds" }. |

`value` reads the number to count from a row; a row whose value is `null`, `undefined` or not a finite number is left out. `bins` is about how many bins: the edges land on round numbers, so the count is close, not exact, and the default is 12. `format` sets how the edges and the tooltip title read. `unit` is the row's name in `one` and `other` forms, `{ one: "fund", other: "funds" }`, and defaults to item and items. `layers` draws your own SVG over the bins: `x` reads values and `y` counts. `active` and `onActiveChange` speak in the bin's index, since rows are counted into bins. Everything else comes from the shared frame: `label`, `summary`, `status`, `onRetry`, `height`, `labels`, `tooltip`, `active`, `onActiveChange` and `locale`; `Chart` documents them. It has no legend and takes no `series`.

## Usage

### When to use
- A set of rows has one number each and the shape of how they spread is the point, such as private funds by gross assets.
- A headline says how many rows there are, and the picture says where most of them lie.

### When not to use
- The groups are named and the amounts are known, such as filings per week. Use BarChart instead.
- A value changes over time. Use LineChart instead.
- Two numbers per row are compared. Use ScatterChart instead.

### Rules
- `rule/histogram-bins-are-a-hint`: When the number of bars must be exact, such as five fixed age bands, draw the counted bands with `BarChart` instead of `Histogram`, because `bins` is about how many: the edges land on round numbers, so the count of bins differs from the number asked for. Evidence: principle heuristic: match between system and real world; single use registry/cobalt/ui/histogram.tsx:38-39. Check: test `histogram.test.tsx` expects 8 values with `bins={4}` to land on the edges 10 to 20.
  - Don't: `<Histogram label="Funds by age band" bins={5} data={funds} value="age" />`
  - Do: `<BarChart label="Funds by age band" data={bands} x="band" series={series} />`
- `rule/histogram-missing-is-null`: When a row has no value, leave it `null` instead of 0, because a row with no value is left out of every bin, while a 0 is counted into the first bin and says something that is not in the data. Evidence: principle heuristic: error prevention, a missing value is not zero. Check: test `histogram.test.tsx` expects a data set of only `null` to show the empty sentence.
  - Don't: `<Histogram label="Funds" data={[{ assets: 0 }]} value="assets" />`
  - Do: `<Histogram label="Funds" data={[{ assets: null }]} value="assets" />`
- `rule/histogram-edges-share-the-format`: When the value is money or a percentage, set `format` so the edges, the tooltip title and the table rows read "$10M to $20M", instead of leaving the plain number format, because the three places read the one `format` and a bare 10000000 beside a headline in dollars is read as a different unit. Evidence: principle heuristic: consistency and standards, one column of figures shares one unit; single use docs/system/examples/histogram/in-card.tsx:22. Check: review of every `Histogram` over a money value, for `format="money"`.
  - Don't: `<Histogram label="Funds by size" data={funds} value="assets" />`
  - Do: `<Histogram label="Funds by size" data={funds} value="assets" format="money" />`

### Content
- Follows `rule/writing-no-invented-numbers`.
- Follows `rule/chart-label-names-the-data`.
- `rule/histogram-unit-names-the-row`: When rows are counted, pass `unit` with the row's name in both forms, such as "fund" and "funds", instead of the default "item" and "items", because the unit is the count's column head in the table, its row in the tooltip and the noun in the sentence "8 funds in 4 ranges". Evidence: principle wcag: 1.1.1 Non-text content; principle heuristic: match between system and real world. Check: test `histogram.test.tsx` expects "Funds by size: 8 funds in".
  - Don't: `<Histogram label="Funds by size" data={funds} value="assets" />`
  - Do: `<Histogram label="Funds by size" data={funds} value="assets" unit={{ one: "fund", other: "funds" }} />`

### Anti-slop
- `rule/histogram-pass-rows-not-counts`: When there are rows with a value each, pass the rows to `Histogram` instead of counting them into bins yourself, because the chart counts on round edges and names the range with the most rows, while a count handed in as `value` would be binned as if it were a measurement. Evidence: principle heuristic: match between system and real world. Check: test `histogram.test.tsx` expects the counts per range and the most-filled range in the sentence.
  - Don't: `<Histogram label="Funds by size" data={bandCounts} value="count" />`
  - Do: `<Histogram label="Funds by size" data={funds} value="assets" />`

### Limits
Not applicable: no measured limit. The hover-cost run in .design-system/evidence/charts/hover-cost.jsonl has no histogram entry, so the count of rows or bins past which it misbehaves is not measured; a histogram draws one bar per bin, not per row.

## Accessibility
Rests on the Chart frame: a focusable `div` with `role="group"` and `aria-roledescription="chart"`, one tab stop. The bins are `aria-hidden`; the data is a visually hidden sentence (`aria-describedby`) naming the count of rows, the number of ranges, the span and the range with the most rows, and a visually hidden `table` with a row per range, such as "10 to 20", and a column for the count headed with the unit's plural. 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 point | the box | by hand |
| Right, Left | the box | the next or previous point | the box | by hand |
| Home, End | the box | the first or the last point | the box | by hand |
| Page Down, Page Up | the box | a tenth of the points 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; 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 point and each series' value as the keys move; pointer moves are silent | by hand |
| table | table | its caption, the `label` | a row header per point | read on request from the table list | test |
| legend item | button | its series 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 |
|---|---|---|
| bins | all | `--chart-1` |
| gridlines | all | `--chart-grid` |
| axis labels | all | `--muted-foreground` |
| crosshair | hover | `--foreground` at 15% |
| marker ring | hover | `--card` |
| tooltip | hover | `--tip`, `--tip-foreground`, `--r-md`, `--t-press`, `--curve` |

## Related
- Chart: the frame every chart type draws in, with the shared states, keys and table.
- BarChart: named groups whose amounts are already known.
- LineChart: a value over time.
- ScatterChart: two numbers per row compared.
- ChartCard: a card with the chart's title and headline figure.
