Skip to main content

Heatmap

Overview​

The Heatmap component draws a grid of cells colored by value, a column per x category and a row per y category, such as a correlation matrix or activity by hour and day.

It comes from the @allxsmith/bestax-charts package, which the Charts guide shows how to install. Recharts has no heatmap, so the chart draws its cells itself, inside a Recharts chart that holds its axes and its tooltip. You give it a row of data per cell, and dataKey names the keys that hold each cell's column, row and value. It colors the cells on a sequential or diverging scale mixed from Bulma colors, shows a legend of the scale and a tooltip in a Bulma box, lets the arrow keys move through the cells, and renders a data table screen readers read.


Import​

import { Heatmap } from '@allxsmith/bestax-charts';

Usage​

Basic Usage​

Each row of data is one cell. dataKey names the key that holds its column (x), its row (y) and its value. The columns and rows follow the order their categories first appear in, and a cell's color runs from a faint tint of primary, for the lowest value, to primary for the highest. label names the chart; it's required, because it's what a screen reader announces.

function example() {
  const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
  const hours = ['0:00', '4:00', '8:00', '12:00', '16:00', '20:00'];
  // Made-up pages: busiest in working hours on weekdays.
  const pages = days.flatMap((day, d) =>
    hours.map((hour, h) => ({
      day,
      hour,
      pages: ((d * 5 + h * 3) % 4) + (d < 5 && h >= 2 && h <= 4 ? 6 : 0),
    }))
  );

  return (
    <Heatmap
      label="On-call pages by hour"
      data={pages}
      dataKey={{ x: 'hour', y: 'day', value: 'pages' }}
      valueLabel="Pages"
    />
  );
}

Diverging Scale​

colorScale="diverging" runs from lowColor at the scale's low end, through the page's background at its middle, to highColor at its high end: danger and info unless you give others. Here, made-up correlations between asset classes run from -1 to 1, and showLabels writes each value in its cell, since a correlation matrix is hard to read by color alone.

function example() {
  const assets = ['Stocks', 'Bonds', 'Gold', 'Real estate', 'Cash'];
  const pairs: Record<string, number> = {
    'Stocks Bonds': -0.3,
    'Stocks Gold': 0.1,
    'Stocks Real estate': 0.7,
    'Stocks Cash': 0,
    'Bonds Gold': 0.3,
    'Bonds Real estate': -0.1,
    'Bonds Cash': 0.2,
    'Gold Real estate': 0.05,
    'Gold Cash': -0.05,
    'Real estate Cash': -0.15,
  };
  const correlations = assets.flatMap(row =>
    assets.map(column => ({
      row,
      column,
      r:
        row === column
          ? 1
          : (pairs[`${row} ${column}`] ?? pairs[`${column} ${row}`]),
    }))
  );

  return (
    <Heatmap
      label="Asset correlations"
      data={correlations}
      dataKey={{ x: 'column', y: 'row', value: 'r' }}
      colorScale="diverging"
      domain={[-1, 1]}
      valueLabel="Correlation"
      valueFormatter={value => value.toFixed(2)}
      showLabels
      height={340}
    />
  );
}

The Scale's Domain​

Without a domain, a sequential scale spans the data's lowest value to its highest, and a diverging one is centered on zero and reaches the value farthest from it. domain sets the ends instead, as [low, high], and a diverging scale takes [low, middle, high] for a middle that isn't halfway between. A value past an end takes that end's color.

function example() {
  const apps = ['Web', 'iOS', 'Android'];
  const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'];
  // Made-up change in signups against each day's target, in percent.
  const change = apps.flatMap((app, a) =>
    days.map((day, d) => ({
      app,
      day,
      change: ((a * 7 + d * 3) % 11) * 10 - 40,
    }))
  );

  return (
    <Heatmap
      label="Signups against target"
      data={change}
      dataKey={{ x: 'day', y: 'app', value: 'change' }}
      colorScale="diverging"
      domain={[-50, 0, 100]}
      valueLabel="Change"
      unit="%"
      showLabels
      height={220}
    />
  );
}

Empty Cells​

A cell no row names, or one whose value isn't a number, is drawn hatched, and the tooltip and the data table say it has no data. The legend shows the hatching when the grid has an empty cell. labels.empty translates what they say.

function example() {
  const failed = [
    { team: 'Web', week: 'W1', failed: 3 },
    { team: 'Web', week: 'W2', failed: 1 },
    { team: 'Web', week: 'W4', failed: 6 },
    { team: 'API', week: 'W1', failed: 2 },
    { team: 'API', week: 'W3', failed: 4 },
    { team: 'Data', week: 'W2', failed: 0 },
    { team: 'Data', week: 'W4', failed: 5 },
  ];

  return (
    <Heatmap
      label="Failed builds by team and week"
      data={failed}
      dataKey={{ x: 'week', y: 'team', value: 'failed' }}
      xCategories={['W1', 'W2', 'W3', 'W4']}
      valueLabel="Failed builds"
      showLabels
      showTable
      height={220}
    />
  );
}

Category Order​

xCategories gives the columns, left to right, and yCategories the rows, top to bottom. A category one lists that no row has is drawn as a column or row of empty cells, and categories the data has that it leaves out follow, in the order they first appear. Above, xCategories puts week 3 before week 4, which the data names first. A category is matched by its text, so '2024' in a list is the year 2024 in the data.

function example() {
  const visits = [
    { size: 'Large', region: 'East', visits: 32 },
    { size: 'Small', region: 'East', visits: 12 },
    { size: 'Medium', region: 'West', visits: 21 },
    { size: 'Small', region: 'West', visits: 8 },
    { size: 'Large', region: 'North', visits: 27 },
  ];

  return (
    <Heatmap
      label="Store visits by size and region"
      data={visits}
      dataKey={{ x: 'size', y: 'region', value: 'visits' }}
      xCategories={['Small', 'Medium', 'Large']}
      yCategories={['North', 'East', 'South', 'West']}
      unit="k"
      showLabels
      height={240}
    />
  );
}

Colors​

highColor and lowColor take a Bulma color name, a shade of one of Bulma's six palette colors (primary-30, info-dark), or any CSS color. The colors between the ends are mixed by the browser with CSS color-mix(), so a Bulma color follows Theme and dark mode, and the scale's background end is the page's own. A sequential scale given a lowColor runs from it to highColor, rather than from the background.

function example() {
  const load = ['A', 'B', 'C', 'D'].flatMap((rack, r) =>
    [1, 2, 3, 4, 5, 6].map(unit => ({
      rack,
      unit,
      load: ((r * 13 + unit * 7) % 10) * 10,
    }))
  );

  return (
    <Heatmap
      label="Server load by rack"
      data={load}
      dataKey={{ x: 'unit', y: 'rack', value: 'load' }}
      lowColor="warning"
      highColor="danger"
      domain={[0, 100]}
      unit="%"
      valueLabel="Load"
      height={220}
    />
  );
}

Legend​

The legend is a strip of the scale's colors with the values at its ends, and its middle on a diverging scale, and a hatched swatch when the grid has an empty cell. valueLabel titles it and heads the value in the tooltip. It sits below the chart; legendPosition="top" moves it above, and hasLegend={false} leaves it off.

function example() {
  const usage = ['Mon', 'Tue', 'Wed'].flatMap((day, d) =>
    ['Morning', 'Afternoon', 'Evening'].map((part, p) => ({
      day,
      part,
      minutes: 20 + ((d * 4 + p * 9) % 7) * 10,
    }))
  );

  return (
    <Heatmap
      label="Minutes in the app"
      data={usage}
      dataKey={{ x: 'day', y: 'part', value: 'minutes' }}
      valueLabel="Minutes"
      legendPosition="top"
      height={200}
    />
  );
}

Axes​

xAxisLabel and yAxisLabel title the axes, and also head the categories in the tooltip. Together they head the data table's first column, as in "Student / Subject", which says what its rows and its columns are. hasXAxis and hasYAxis turn an axis off, and xAxisProps and yAxisProps go to Recharts' XAxis and YAxis after the chart's own, such as orientation: 'top' for the column names above the grid.

function example() {
  const scores = ['Ana', 'Ben', 'Cy'].flatMap((student, s) =>
    ['Math', 'Art', 'Music', 'History'].map((subject, j) => ({
      student,
      subject,
      score: 55 + ((s * 11 + j * 17) % 45),
    }))
  );

  return (
    <Heatmap
      label="Test scores"
      data={scores}
      dataKey={{ x: 'subject', y: 'student', value: 'score' }}
      xAxisLabel="Subject"
      yAxisLabel="Student"
      xAxisProps={{ orientation: 'top' }}
      domain={[0, 100]}
      showLabels
      height={220}
    />
  );
}

Formatting Values​

Values are written as useNumberFormat writes a number, in the LocaleProvider's locale. valueFormatter writes them your way instead, in the tooltip, the legend, the cells and the data table, and unit is written after each one. Categories are written as they are in the data.

function example() {
  return (
    <LocaleProvider locale="de-DE">
      <Heatmap
        label="Umsatz nach Filiale und Quartal"
        data={[
          { store: 'Nord', quarter: 'Q1', sales: 1250.5 },
          { store: 'Nord', quarter: 'Q2', sales: 1480.25 },
          { store: 'Süd', quarter: 'Q1', sales: 980.75 },
          { store: 'Süd', quarter: 'Q2', sales: 1120 },
        ]}
        dataKey={{ x: 'quarter', y: 'store', value: 'sales' }}
        valueLabel="Umsatz"
        unit=" €"
        labels={{ empty: 'Keine Daten' }}
        showLabels
        showTable
        height={180}
      />
    </LocaleProvider>
  );
}

Recharts Props and Children​

chartProps goes to the Recharts ScatterChart that holds the drawing, after the chart's own props (here, margin), tooltipProps to its Tooltip, and xAxisProps and yAxisProps to its axes. children adds more Recharts elements, imported from recharts, such as a ReferenceArea over a block of cells, named by their categories: here, the lunch hours. The pointer still finds the cells under it.

import { ReferenceArea } from 'recharts';

function example() {
  const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'];
  const hours = ['9:00', '11:00', '13:00', '15:00', '17:00'];
  const meetings = days.flatMap((day, d) =>
    hours.map((hour, h) => ({ day, hour, meetings: (d * 3 + h * 2) % 5 }))
  );

  return (
    <Heatmap
      label="Meetings by hour"
      data={meetings}
      dataKey={{ x: 'hour', y: 'day', value: 'meetings' }}
      chartProps={{ margin: { top: 24, right: 10, bottom: 0, left: 0 } }}
      height={260}
    >
      <ReferenceArea
        x1="13:00"
        x2="13:00"
        fill="none"
        stroke="var(--bulma-danger)"
        strokeWidth={2}
        strokeDasharray="6 4"
        label={{
          value: 'Lunch',
          position: 'top',
          fill: 'var(--bulma-text)',
          fontSize: 12,
        }}
      />
    </Heatmap>
  );
}

Size​

The chart fills its container's width and is 300 pixels tall. width and height take pixels or a percentage of the container, and the cells share the room the axes leave. A chart sized in pixels draws on the server as well; one sized in percent draws once the browser has measured its container, and follows it as it changes. Its legend and data table render on the server either way.

<Heatmap
  label="Two by two"
  data={[
    { x: 'A', y: 'One', value: 1 },
    { x: 'B', y: 'One', value: 2 },
    { x: 'A', y: 'Two', value: 3 },
    { x: 'B', y: 'Two', value: 4 },
  ]}
  dataKey={{ x: 'x', y: 'y', value: 'value' }}
  width={320}
  height={180}
/>


Theming​

The cells are parted by --bulma-chart-stroke-color, an empty cell's hatching and the legend's empty swatch are drawn in --bulma-chart-grid-color, the values in the cells in --bulma-chart-label-color with a halo of --bulma-chart-stroke-color, and the ticks and the legend's values in --bulma-chart-text-color. The scale fades to --bulma-scheme-main, the page's own background. The BarChart's Theming section lists the other variables the charts draw with.

:root {
--bulma-chart-stroke-color: var(--bulma-scheme-main); /* between cells */
--bulma-chart-grid-color: var(--bulma-border); /* empty cells' hatching */
--bulma-chart-label-color: var(--bulma-text-strong); /* values in the cells */
}

Accessibility​

  • The chart is a <figure> named by label, which also captions the data table. The drawing's <svg> takes the same name and description through aria-labelledby and aria-describedby.
  • A data table of the grid renders beside the drawing, visually hidden with Bulma's is-sr-only, so a screen reader reads the value each color shows (WAI: complex images). It has a row per y category and a column per x category, each headed, so a screen reader names a cell's row and column as it reads its value, and an empty cell says it has no data. Its corner names both axes, such as "Day / Hour". showTable puts it on screen.
  • The drawing is a tab stop, its first cell ringed the first time Tab reaches it, and the cell the keyboard was last on after that. The arrow keys move a column or a row the way they point, and stop at the grid's edges; Home and End go to the left and right ends of the row, and Ctrl+Home and Ctrl+End to the grid's top left and bottom right cells, whichever way an axis runs. The tooltip shows the ringed cell's categories and value, and Escape hides it. The ring is drawn in two colors, dark and light in either color mode, so it shows on any cell, and above anything drawn over the cells. A click that focuses the drawing leaves the ring off until a key moves it. The pointer takes over from the keyboard when it moves onto a cell, even one under a ReferenceArea, and the arrow keys then go on from that cell.
  • The legend is a key to the colors, so it's aria-hidden; a screen reader reads each value from the data table instead.
  • Values are told by color alone in the drawing unless showLabels writes them in the cells, in the strong text color with a halo of the background, which reads on a cell of any color. An empty cell is hatched, not only left blank, so it isn't mistaken for a value at the scale's background end.
  • Browsers leave an <svg> in its own colors in forced colors mode, so the cells keep the scale's colors there too, and the values in the cells, the tooltip and the data table read as they do elsewhere.

  • ScatterChart: Points by two values, whose dataKey takes the same object form.
  • BarChart: Values drawn as bars, one group per category.
  • Table: The Bulma table the chart's data table is drawn with.
  • LocaleProvider: The locale the chart writes its numbers in.
  • Helper Props: Bulma helper props for spacing, color, etc.

Additional Resources​


Props​

PropTypeDefaultDescription
datareadonly ChartRow[]—Required. The cells to draw: one row each, with the keys dataKey names for its column, its row and its value. A pair of categories no row names, or a row whose value isn't a number, is drawn as an empty cell, which the tooltip and the data table call empty. A row whose x or y isn't a string or a number is left out, and when two rows name the same cell, the first is drawn.
dataKey{ x: string; y: string; value: string }—Required. The keys of each row that hold its cell: x its column, y its row and value the number its color shows. A key with dots or brackets, such as pair.from, reads a nested value, as Recharts does, unless a row has that key itself.
xCategoriesreadonly ChartCategory[]—The x categories, in the order the columns are drawn from the left. A category listed here that no row has is drawn as a column of empty cells, and categories data has that this leaves out follow the ones it lists, in the order they first appear. Without it, the columns follow the order their categories first appear in data. A category is matched by its text, so '2024' here is the year 2024 in the data.
yCategoriesreadonly ChartCategory[]—The y categories, in the order the rows are drawn from the top. A category listed here that no row has is drawn as a row of empty cells, and categories data has that this leaves out follow the ones it lists, in the order they first appear. Without it, the rows follow the order their categories first appear in data. A category is matched by its text, as in xCategories.
colorScale'sequential' | 'diverging''sequential'How the colors run. sequential runs from a faint tint of highColor at the scale's low end to highColor at its high end, for values that run one way, such as counts. diverging runs from lowColor at the low end, through the page's background at its middle, to highColor at the high end, for values on either side of a middle, such as correlations.
highColorChartColor'primary' on a sequential scale, 'info' on a diverging oneThe color of the scale's high end: a Bulma name, which follows Theme and dark mode, or a CSS color. The colors between are mixed from it by the browser with color-mix(), which takes a color and not a url() pattern.
lowColorChartColor'danger' on a diverging scaleThe color of the scale's low end, a Bulma name or a CSS color, as highColor takes. A sequential scale runs from this color, rather than from a tint of highColor, when it's given.
domain[number, number] | [number, number, number]—The values at the scale's ends: [low, high], or [low, middle, high] on a diverging scale, whose middle is otherwise halfway between. A value past an end takes that end's color. Without one, a sequential scale spans the data's lowest value to its highest, and a diverging one is centered on zero and reaches the value farthest from it.
showLabelsbooleanfalseWrites each cell's value inside it, where it fits, in the strong text color with a halo of the page's background, so it reads on any cell.
hasLegendbooleantrueShows a legend of the color scale: a strip of its colors with the values at its ends (and its middle, on a diverging scale), and a swatch for an empty cell when the grid has one. A grid with no values and no domain has no strip, since it has no span to show. The legend is a key to the colors, so screen readers skip it and read each value from the data table.
legendPosition'top' | 'bottom''bottom'Where the legend sits.
hasXAxisbooleantrueDraws the x axis.
hasYAxisbooleantrueDraws the y axis.
xAxisLabelstring—A title for the x axis. It also heads the x category in the tooltip, and the data table's first column after the y axis title, as in "Day / Hour", which use dataKey.x without one.
yAxisLabelstring—A title for the y axis. It also heads the y category in the tooltip and the data table's first column, before the x axis title, which use dataKey.y without one.
valueLabelstring—What the values are, such as "Correlation". It titles the legend and heads the value in the tooltip, which uses dataKey.value without one.
labels{ empty?: string }—The text the chart writes itself, in the tooltip, the table and the legend, to translate.
valueFormatterChartValueFormatter—Writes each value in the tooltip, the legend, the cells and the data table. Without one, values are written as useNumberFormat writes a number, in the LocaleProvider's locale. The categories are written as the data has them.
childrenReact.ReactNode—More Recharts elements to draw inside the chart, such as a ReferenceArea over a block of cells, named by their categories.
xAxisPropsPartial<XAxisProps>—Props passed to Recharts' XAxis, after the chart's own, such as orientation.
yAxisPropsPartial<YAxisProps>—Props passed to Recharts' YAxis, after the chart's own.
tooltipPropsPartial<TooltipProps>—Props passed to Recharts' Tooltip, after the chart's own.
chartPropsPartial<React.ComponentProps<typeof RechartsScatterChart>>—Props passed to Recharts' ScatterChart, which holds the drawing, after the chart's own, such as margin.
classNamestring—Additional CSS classes to apply.
labelstring—Required. What the chart shows, such as "Monthly sales". It names the chart for assistive tech, and captions its data table. Shown above the chart with showLabel.
descriptionstring—A sentence or two on what the chart says, such as the trend it shows. A screen reader reads it with the chart's name. Not shown on screen.
showLabelbooleanfalseShows label above the chart as its caption.
showTablebooleanfalseShows the chart's data table below it. The table is always there for screen readers, which read the numbers from it; this puts it on screen as well.
hasTooltipbooleantrueShows a tooltip with the values under the pointer, or under the keyboard focus as the arrow keys move through the chart.
unitstring—Written after every value, such as % or kg.
widthChartSize'100%'The chart's width, in pixels or as a percentage of its container. A percentage makes the chart follow its container's size as the browser measures it. Recharts draws in the browser either way: a server render holds the figure, its caption, legend and data table, and the drawing appears once the page hydrates.
heightChartSize300The chart's height, in pixels or as a percentage of its container, which then needs a height of its own.
refReact.Ref<HTMLElement>—Ref forwarded to the root <figure>.
...All standard HTML attributes and Bulma helper props—See Helper Props

Types:

  • ChartCategory: string | number — A category on one of a grid chart's axes, such as a day or an asset.
  • ChartColor: Bulma color | `${(typeof paletteColors)[number]}-${(typeof validColorShades)[number]}` | (string & {}) — A color for a series, a slice or a mark. A Bulma color name such as primary or grey-light, a shade of one of Bulma's six palette colors such as primary-60 or info-dark, or any CSS color, such as #3e8ed0, var(--brand) or url(#stripes) for a pattern the chart's children define. A Bulma name draws with Bulma's own CSS variable, so it follows Theme and dark mode.
  • ChartRow: Record<string, any> — One row of a chart's data: an object whose keys the chart's dataKey and series name.
  • ChartSize: number | `${number}%` — A chart's width or height: pixels, or a percentage of its container.
  • ChartValueFormatter: (value: number) => string — Writes a value for the axes, the tooltip, the labels and the data table.