# HeatMap

> Heat maps from @salmonui/charts/heat-map with category, numeric and time axes, label groups, gradient and step color scales, bubbles, legends, selection, tooltips and a canvas renderer for a million cells.

Canonical: https://salmonui.dev/docs/data-visualization/heat-map

`HeatMap` lives in `@salmonui/charts/heat-map`. `data` is a 2D table
(`data[row][column]`, rows are y) or records read through `xField`,
`yField` and `valueField`; `sizeField` adds a second value for bubbles.

```tsx
import { HeatMap } from '@salmonui/charts/heat-map';
import '@salmonui/charts/heat-map/styles.css';

<HeatMap data={table} xAxis={{ labels: days }} yAxis={{ labels: hours }} cells={{ labels: true }} height={360} />
```

### Live demo: Heat map with step legend

Live demo: https://salmonui.dev/demos/data-visualization/heat-map-basic

A HeatMap of load by weekday and hour with cell labels, a step color scale of data colors, a toggling list legend, multiple selection and hour groups.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { HeatMap, type HeatMapCellRef } from '@salmonui/charts/heat-map';

const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
const hours = ['00', '04', '08', '12', '16', '20'];
const load = hours.map((_, y) => days.map((_, x) => ((x * 5 + y * 11) % 17) + (x < 5 && y > 1 && y < 5 ? 6 : 0)));

export default function HeatMapBasicDemo() {
  const [selected, setSelected] = useState<readonly HeatMapCellRef[]>([]);
  return (
    <div className="demo-stack">
      <HeatMap
        title="Load by weekday and hour"
        data={load}
        height={360}
        xAxis={{ labels: days, labelGroups: [{ from: 0, to: 4, text: 'Weekdays' }, { from: 5, to: 6, text: 'Weekend' }] }}
        yAxis={{ labels: hours, title: 'Hour' }}
        cells={{ labels: true }}
        colorScale={{ kind: 'steps', stops: [{ value: 0, color: '#4c87e4', label: 'Low' }, { value: 8, color: '#4278d8', label: 'Medium' }, { value: 16, color: '#2e59c2', label: 'High' }] }}
        selection={{ multiple: true }}
        selectedCells={selected}
        onSelectedCellsChange={setSelected}
      />
      <p className="demo-status" aria-live="polite">
        Selected: <code>{selected.map((c) => `${days[c.x]} ${hours[c.y]}`).join(', ') || 'none'}</code>
      </p>
    </div>
  );
}
```

## Axes

`xAxis` and `yAxis` take `labels`, `scale` (`'category'`, `'linear'` or
`'time'`: numeric and time keys are sorted and filtered by `min` / `max`),
`interval` (every n-th label), `format` (`Intl` options or a function of the
key), `labelOverlap` (`'none'`, `'hide'`, `'trim'`, `'wrap'`, `'rotate45'`,
`'rotate90'`), `maxLabelWidth`, `position`
(`'bottom'` / `'top'`, `'start'` / `'end'`), `reversed`, `title` and
`labelGroups: [{ from, to, text }]` for a second level of labels. Time keys
format in `timeZone` (UTC by default, so server and client agree).

## Colors and legend

Without stops the cells use the derived sequential roles
(`--salmon-chart-sequential-1..9`). `colorScale` takes data colors:
`{ kind: 'gradient' | 'steps', stops: [{ value, color, label }], domain:
'all' | 'row' | 'column', outOfRange }`. A gradient scale shows a gradient
legend; a steps scale shows a list legend whose toggle buttons hide the cells
of a step through `hiddenItems` / `defaultHiddenItems` /
`onHiddenItemsChange` (indices of the steps stops). `legend` is `true` or
`{ position: 'top' | 'bottom' | 'start' | 'end', title, labels: 'all' |
'edge' | 'none', format, toggle }`. Empty cells
(null) use the neutral empty color and read "No value" in the table.

`cells: { labels, format, shape: 'rect' | 'bubble', bubble: 'size' | 'color'
| 'sizeAndColor' | 'sector', highlight }`. `formatCell(cell)` changes the
label text and `getCellStyle(cell)` the color.

## Selection, events and tooltip

`selection` (`true` or `{ multiple }`) toggles cells on click, Enter and
Space. Selection is controlled with `selectedCells` + `onSelectedCellsChange`
or uncontrolled with `defaultSelectedCells`; cells are `{ x, y }` column and
row indices, and the event carries `source` and `reason` (`'click'` or
`'keyboard'`).

```tsx
import { useState } from 'react';
import { HeatMap, type HeatMapCellRef } from '@salmonui/charts/heat-map';

function Picker({ table }: { table: number[][] }) {
  const [selected, setSelected] = useState<readonly HeatMapCellRef[]>([]);
  return <HeatMap data={table} selection={{ multiple: true }} selectedCells={selected} onSelectedCellsChange={setSelected} height={300} />;
}
```

`onCellClick(cell, event)`, `onCellDoubleClick(cell)` and
`onCellHover(cell | null)` report a `HeatMapCell` (`x`, `y`, `xKey`, `yKey`,
`value`, `size`, `color`). The tooltip (`tooltip: true` or `{ render(cell)
}`) is driven by the store: a pointer move that stays in a cell re-renders
nothing.

### Live demo: Bubble heat map with custom cells

Live demo: https://salmonui.dev/demos/data-visualization/heat-map-bubbles

A survey HeatMap of records with a value and a size field drawn as bubbles, long axis labels that trim or wrap, axis position and reversal, a title and subtitle, a custom tooltip, click and double-click events, formatCell and getCellStyle.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { HeatMap, type HeatMapAxis, type HeatMapCell } from '@salmonui/charts/heat-map';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { Select } from '@salmonui/dropdowns/select';

const teams = ['Customer onboarding', 'Payments platform', 'Search and discovery', 'Mobile experience', 'Data infrastructure'];
const quarters = ['Q1 2026', 'Q2 2026', 'Q3 2026', 'Q4 2026'];
// Engagement score (0-100) and the number of survey responses per team and quarter.
const survey = teams.flatMap((team, t) =>
  quarters.map((quarter, q) => ({
    team,
    quarter,
    score: 52 + ((t * 13 + q * 7) % 41),
    responses: 8 + ((t * 5 + q * 3) % 24),
  })),
);

type Overlap = NonNullable<HeatMapAxis['labelOverlap']>;
type Bubble = 'size' | 'color' | 'sizeAndColor' | 'sector';

/** Survey scores as bubbles: value sets the color, responses the size. */
export default function HeatMapBubblesDemo() {
  const [bubble, setBubble] = useState<Bubble>('sizeAndColor');
  const [overlap, setOverlap] = useState<Overlap>('trim');
  const [xTop, setXTop] = useState(false);
  const [reversed, setReversed] = useState(false);
  const [last, setLast] = useState('none');
  const describe = (c: HeatMapCell) => `${c.yKey}, ${c.xKey}: ${c.value} (${c.size ?? 0} responses)`;
  return (
    <div className="demo-stack">
      <div className="demo-toolbar" role="group" aria-label="Heat map options">
        <label>
          Bubble
          <Select aria-label="Bubble" data={[{ value: 'size', label: 'Size' }, { value: 'color', label: 'Color' }, { value: 'sizeAndColor', label: 'Size and color' }, { value: 'sector', label: 'Sector' }]} value={bubble} onValueChange={(value) => value != null && setBubble(value as Bubble)} />
        </label>
        <label>
          Row labels
          <Select aria-label="Row labels" data={[{ value: 'trim', label: 'Trim' }, { value: 'wrap', label: 'Wrap' }, { value: 'none', label: 'None' }]} value={overlap} onValueChange={(value) => value != null && setOverlap(value as Overlap)} />
        </label>
        <Checkbox checked={xTop} onCheckedChange={(checked) => setXTop(checked)}>
          Quarters on top
        </Checkbox>
        <Checkbox checked={reversed} onCheckedChange={(checked) => setReversed(checked)}>
          Reverse teams
        </Checkbox>
      </div>
      <HeatMap
        title="Engagement survey"
        subtitle="Bubble size: number of responses"
        data={survey}
        xField="quarter"
        yField="team"
        valueField="score"
        sizeField="responses"
        height={380}
        xAxis={{ labels: quarters, position: xTop ? 'top' : 'bottom', labelOverlap: 'rotate45' }}
        yAxis={{ labels: teams, labelOverlap: overlap, maxLabelWidth: 120, reversed }}
        cells={{ shape: 'bubble', bubble, labels: true }}
        colorScale={{ stops: [{ value: 50, color: '#a16207' }, { value: 70, color: '#059669' }, { value: 92, color: '#0a7354' }] }}
        legend={{ position: 'end', title: 'Score' }}
        formatCell={(c) => (c.value >= 85 ? `${c.value}★` : String(c.value))}
        getCellStyle={(c) => ((c.size ?? 0) < 12 ? { color: '#6b7280' } : undefined)}
        tooltip={{
          render: (c) => (
            <span>
              <strong>{c.yKey}</strong>, {c.xKey}: score {c.value}, {c.size ?? 0} responses
              {(c.size ?? 0) < 12 ? ' (too few to trust)' : ''}
            </span>
          ),
        }}
        onCellClick={(c) => setLast(`click ${describe(c)}`)}
        onCellDoubleClick={(c) => setLast(`double click ${describe(c)}`)}
      />
      <p className="demo-status" aria-live="polite">
        Last event: <code>{last}</code>
      </p>
    </div>
  );
}
```

## Large matrices

`renderer` is `'svg'`, `'canvas'` or `'auto'` (default): from 10,000 cells
the cells draw on a lazily loaded canvas (one pixel per cell, scaled), while
axes, legend, labels and the accessible table stay SVG and DOM. A
1,000 × 1,000 heat map mounts within 200 ms and hit-testing is index
arithmetic. The server renders the axes and an empty, sized canvas.

### Live demo: Large heat map on canvas

Live demo: https://salmonui.dev/demos/data-visualization/heat-map-large

A 400 × 400 HeatMap (160,000 cells) that switches to the canvas renderer automatically, with a gradient of data colors per row.

`Demo.tsx`:

```tsx
'use client';

import { useMemo } from 'react';
import { HeatMap } from '@salmonui/charts/heat-map';

// A 40 x 40 block of null values shows the empty-cell color.
export default function HeatMapLargeDemo() {
  const data = useMemo(() => Array.from({ length: 400 }, (_, y) => Array.from({ length: 400 }, (_, x) => x >= 300 && x < 340 && y >= 120 && y < 160 ? null : Math.sin(x / 25) * Math.cos(y / 18) + y / 400)), []);
  return <HeatMap title="160,000 cells" data={data} height={420} xAxis={{ interval: 50 }} yAxis={{ interval: 50 }} colorScale={{ domain: 'row', stops: [{ value: 0, color: '#fef3c7' }, { value: 1, color: '#b45309' }] }} />;
}
```

## Keyboard and accessibility

One tab stop; arrow keys move by cell (reversed axes flip their arrows),
Home / End to the row ends (with Ctrl to the corners), PageUp / PageDown to
the first and last row, Enter or Space selects, Escape hides the tooltip. The
focused cell is announced ("08, Wed: 12"). The table lists the cells, capped
with a summary row for large matrices (`showDataTable` shows it). `title`
and `subtitle` label the figure; `description` replaces the automatic
summary.

## Server rendering and API

The server renders the final SVG markup (or the sized empty canvas) at
`width` / `height`, and time keys format in `timeZone`, so hydration matches;
tooltips are client only. `animated` (default `true`) runs the entrance
transition after hydration with the opt-in
`@salmonui/charts/viz-animations.css`; it is off under
`prefers-reduced-motion`. `onResize` reports size changes.

`ref` receives a `HeatMapApi`: `element`, `export(options)`, `toBlob`,
`toDataURL`, `toSVGString`, `print()` and `focus()`. Every prop and type is
in the [API reference](https://salmonui.dev/docs/reference/charts/heat-map).

Custom content uses render props (`tooltip.render`, `formatCell`,
`getCellStyle`), not HTML string templates; colors follow the theme and
visual tokens are system-owned (see [Rendering and colors](https://salmonui.dev/docs/data-visualization/rendering-and-colors)).
