Skip to main content

AreaChart

Overview​

The AreaChart component draws values as filled areas across the categories, one over another, stacked, as shares of a whole or split in two colors at zero.

It wraps Recharts' AreaChart and comes from the @allxsmith/bestax-charts package, which the Charts guide shows how to install. You give it rows of data, the dataKey that holds each row's category, and the series to draw, and it draws them with Bulma's colors, a legend whose entries hide and show series, a tooltip in a Bulma box, and a data table screen readers read.


Import​

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

Usage​

Basic Usage​

Each row of data is a category, and each series names the key of the rows that holds its values. label names the chart; it's required, because it's what a screen reader announces.

function example() {
  const traffic = [
    { month: 'Jan', organic: 1860, paid: 800 },
    { month: 'Feb', organic: 3050, paid: 2000 },
    { month: 'Mar', organic: 2370, paid: 1200 },
    { month: 'Apr', organic: 730, paid: 1900 },
    { month: 'May', organic: 2090, paid: 1300 },
  ];

  return (
    <AreaChart
      label="Traffic by source"
      data={traffic}
      dataKey="month"
      series={[
        { name: 'organic', label: 'Organic', color: 'primary' },
        { name: 'paid', label: 'Paid', color: 'info' },
      ]}
      hasLegend
    />
  );
}

Stacked and Percent​

type="stacked" stacks the areas one on another, so the top edge shows the total. type="percent" stacks them to the same height, so each category shows its split, and the value axis reads in percent. The tooltip and the data table still show the values the data holds.

function example() {
  const traffic = [
    { month: 'Jan', organic: 1860, paid: 800, referral: 420 },
    { month: 'Feb', organic: 3050, paid: 2000, referral: 610 },
    { month: 'Mar', organic: 2370, paid: 1200, referral: 580 },
    { month: 'Apr', organic: 730, paid: 1900, referral: 690 },
  ];
  const series = [
    { name: 'organic', label: 'Organic', color: 'primary' },
    { name: 'paid', label: 'Paid', color: 'info' },
    { name: 'referral', label: 'Referral', color: 'warning' },
  ];

  return (
    <Columns>
      <Column>
        <AreaChart
          label="Traffic, stacked"
          showLabel
          type="stacked"
          data={traffic}
          dataKey="month"
          series={series}
          height={240}
        />
      </Column>
      <Column>
        <AreaChart
          label="Traffic, as shares"
          showLabel
          type="percent"
          data={traffic}
          dataKey="month"
          series={series}
          height={240}
        />
      </Column>
    </Columns>
  );
}

To stack some series and not others, leave type at its default and give the series that stack together the same stackId.

Split at Zero​

type="split" draws the first series alone, in one color above zero and another below it, the way a balance or a profit runs. splitColors sets the two, success and danger unless you name others. A reference line at zero makes the split easy to read.

function example() {
  const cashFlow = [
    { month: 'Jan', net: 1200 },
    { month: 'Feb', net: 800 },
    { month: 'Mar', net: -400 },
    { month: 'Apr', net: -900 },
    { month: 'May', net: 300 },
    { month: 'Jun', net: 1500 },
  ];

  return (
    <AreaChart
      label="Net cash flow"
      type="split"
      data={cashFlow}
      dataKey="month"
      series={[{ name: 'net', label: 'Net' }]}
      referenceLines={[{ y: 0 }]}
      hasDots
    />
  );
}

Fill​

Each area fades from its top to its bottom, so an area of positive values is strongest along its edge. fillOpacity sets the opacity it starts from, 0.2 unless you set it, and hasGradient={false} fills each area with one flat color at that opacity instead.

function example() {
  const traffic = [
    { month: 'Jan', organic: 1860, paid: 800 },
    { month: 'Feb', organic: 3050, paid: 2000 },
    { month: 'Mar', organic: 2370, paid: 1200 },
    { month: 'Apr', organic: 730, paid: 1900 },
  ];
  const series = [
    { name: 'organic', label: 'Organic', color: 'primary' },
    { name: 'paid', label: 'Paid', color: 'info' },
  ];

  return (
    <Columns>
      <Column>
        <AreaChart
          label="Stronger gradient"
          showLabel
          data={traffic}
          dataKey="month"
          series={series}
          fillOpacity={0.6}
          height={220}
        />
      </Column>
      <Column>
        <AreaChart
          label="Flat fill"
          showLabel
          data={traffic}
          dataKey="month"
          series={series}
          hasGradient={false}
          fillOpacity={0.35}
          height={220}
        />
      </Column>
    </Columns>
  );
}

Curves, Dots and Gaps​

curveType sets how the areas' edges run between their points, as on LineChart, and a series' own curveType wins. hasDots draws a dot on each point, and a series' strokeDasharray dashes its edge. An area runs across a gap in the data unless connectNulls={false} breaks it there.

function example() {
  const requests = [
    { day: 'Mon', requests: 4200 },
    { day: 'Tue', requests: 4800 },
    { day: 'Wed', requests: null },
    { day: 'Thu', requests: 5100 },
    { day: 'Fri', requests: 5600 },
    { day: 'Sat', requests: 3100 },
  ];

  return (
    <AreaChart
      label="Requests per day"
      data={requests}
      dataKey="day"
      series={[
        {
          name: 'requests',
          label: 'Requests',
          color: 'success',
          curveType: 'step',
        },
      ]}
      connectNulls={false}
      hasDots
    />
  );
}

Vertical​

orientation="vertical" lays the categories down the side, with the areas running across.

function example() {
  const traffic = [
    { month: 'Jan', organic: 1860, paid: 800 },
    { month: 'Feb', organic: 3050, paid: 2000 },
    { month: 'Mar', organic: 2370, paid: 1200 },
    { month: 'Apr', organic: 730, paid: 1900 },
  ];

  return (
    <AreaChart
      label="Traffic by source"
      orientation="vertical"
      grid="vertical"
      type="stacked"
      data={traffic}
      dataKey="month"
      series={[
        { name: 'organic', label: 'Organic', color: 'primary' },
        { name: 'paid', label: 'Paid', color: 'info' },
      ]}
      hasLegend
      height={260}
    />
  );
}

Axes, Grid and Labels​

xAxisLabel and yAxisLabel title the axes, and hasXAxis and hasYAxis turn them off. grid picks the grid lines: horizontal (the default), vertical, both or none. showLabels writes each value above its point, the value the data holds even on a stacked chart.

function example() {
  const visits = [
    { day: 'Mon', visits: 320 },
    { day: 'Tue', visits: 410 },
    { day: 'Wed', visits: 380 },
    { day: 'Thu', visits: 450 },
    { day: 'Fri', visits: 290 },
  ];

  return (
    <AreaChart
      label="Visits per day"
      data={visits}
      dataKey="day"
      series={[{ name: 'visits', label: 'Visits', color: 'link' }]}
      xAxisLabel="Day"
      yAxisLabel="Visits"
      grid="both"
      showLabels
    />
  );
}

Two Value Axes​

hasRightYAxis draws a second value axis on the right, for the series whose yAxisId is right, when two series run on different scales.

function example() {
  const server = [
    { hour: '09:00', requests: 4200, errors: 12 },
    { hour: '10:00', requests: 5300, errors: 18 },
    { hour: '11:00', requests: 6100, errors: 9 },
    { hour: '12:00', requests: 5800, errors: 25 },
  ];

  return (
    <AreaChart
      label="Requests and errors"
      data={server}
      dataKey="hour"
      series={[
        { name: 'requests', label: 'Requests', color: 'primary' },
        { name: 'errors', label: 'Errors', color: 'danger', yAxisId: 'right' },
      ]}
      hasRightYAxis
      yAxisLabel="Requests"
      rightYAxisLabel="Errors"
      hasLegend
    />
  );
}

Reference Lines​

referenceLines draws lines across the chart at a value (y) or a category (x), each with an optional label and color.

function example() {
  const storage = [
    { month: 'Jan', used: 420 },
    { month: 'Feb', used: 510 },
    { month: 'Mar', used: 640 },
    { month: 'Apr', used: 730 },
  ];

  return (
    <AreaChart
      label="Storage used"
      data={storage}
      dataKey="month"
      series={[{ name: 'used', label: 'Used', color: 'warning' }]}
      unit=" GB"
      referenceLines={[{ y: 800, label: 'Quota', color: 'danger' }]}
    />
  );
}

Legend and Hidden Series​

hasLegend draws a legend below the chart, or above it with legendPosition="top". Each entry is a toggle button that hides or shows its series. The chart keeps that state itself, starting from defaultHiddenSeries, or you hold it with hiddenSeries and onHiddenSeriesChange.

function example() {
  const traffic = [
    { month: 'Jan', organic: 1860, paid: 800, referral: 420 },
    { month: 'Feb', organic: 3050, paid: 2000, referral: 610 },
    { month: 'Mar', organic: 2370, paid: 1200, referral: 580 },
  ];
  const [hidden, setHidden] = useState(['referral']);

  return (
    <>
      <Buttons mb="3">
        <Button size="small" onClick={() => setHidden([])}>
          Show all
        </Button>
      </Buttons>
      <AreaChart
        label="Traffic by source"
        type="stacked"
        data={traffic}
        dataKey="month"
        series={[
          { name: 'organic', label: 'Organic', color: 'primary' },
          { name: 'paid', label: 'Paid', color: 'info' },
          { name: 'referral', label: 'Referral', color: 'warning' },
        ]}
        hasLegend
        legendPosition="top"
        hiddenSeries={hidden}
        onHiddenSeriesChange={setHidden}
      />
    </>
  );
}

Formatting Values​

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

function example() {
  const revenue = [
    { quarter: 'Q1', revenue: 48200 },
    { quarter: 'Q2', revenue: 53900 },
    { quarter: 'Q3', revenue: 61400 },
    { quarter: 'Q4', revenue: 58800 },
  ];
  const dollars = new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD',
    maximumFractionDigits: 0,
  });

  return (
    <AreaChart
      label="Revenue by quarter"
      data={revenue}
      dataKey="quarter"
      series={[{ name: 'revenue', label: 'Revenue', color: 'success' }]}
      valueFormatter={value => dollars.format(value)}
    />
  );
}

Colors​

A series' color takes a Bulma color name (primary, info, grey-dark and the rest), a shade of one of Bulma's six palette colors (primary-30, info-dark), or any CSS color. Bulma names draw with Bulma's own CSS variables, so they follow Theme and dark mode. A series with no color takes the next of Bulma's palette colors.

function example() {
  const energy = [
    { month: 'Jan', solar: 20, wind: 45, hydro: 35 },
    { month: 'Feb', solar: 28, wind: 40, hydro: 32 },
    { month: 'Mar', solar: 39, wind: 36, hydro: 30 },
    { month: 'Apr', solar: 48, wind: 30, hydro: 29 },
  ];

  return (
    <AreaChart
      label="Energy by source"
      type="percent"
      data={energy}
      dataKey="month"
      series={[
        { name: 'solar', label: 'Solar', color: 'success-30' },
        { name: 'wind', label: 'Wind', color: 'success-50' },
        { name: 'hydro', label: 'Hydro', color: 'success-70' },
      ]}
      hasGradient={false}
      fillOpacity={0.8}
      hasLegend
      height={240}
    />
  );
}

Showing the Data Table​

The data table is always there for screen readers. showTable puts it on screen too, below the chart, and showLabel shows the chart's label above it as a caption.

function example() {
  const traffic = [
    { month: 'Jan', organic: 1860, paid: 800 },
    { month: 'Feb', organic: 3050, paid: 2000 },
    { month: 'Mar', organic: 2370, paid: 1200 },
  ];

  return (
    <AreaChart
      label="Traffic by source"
      showLabel
      showTable
      data={traffic}
      dataKey="month"
      series={[
        { name: 'organic', label: 'Organic' },
        { name: 'paid', label: 'Paid' },
      ]}
      height={200}
    />
  );
}

Recharts Props and Children​

Each Recharts part the chart draws takes its own props after the chart's: areaProps for every Area (here, filling down to the smallest value rather than zero), chartProps for Recharts' AreaChart, and xAxisProps, yAxisProps, rightYAxisProps and tooltipProps. children adds more Recharts elements, such as a ReferenceArea, a Brush, or <defs> for a pattern a series names with url(#id).

function example() {
  const price = [
    { day: 'Mon', price: 182 },
    { day: 'Tue', price: 185 },
    { day: 'Wed', price: 180 },
    { day: 'Thu', price: 188 },
    { day: 'Fri', price: 192 },
  ];

  return (
    <AreaChart
      label="Closing price"
      data={price}
      dataKey="day"
      series={[{ name: 'price', label: 'Price', color: 'link' }]}
      areaProps={{ baseValue: 'dataMin' }}
      yAxisProps={{ domain: ['dataMin', 'dataMax'] }}
      chartProps={{ margin: { top: 16, right: 16, bottom: 0, left: 0 } }}
    />
  );
}

Size​

The chart fills its container's width and is 300 pixels tall. height changes that, and width and height take pixels or a percentage of the container. A chart sized in percent draws once the browser has measured its container, and its legend and data table render on the server either way.

<AreaChart
  label="Two months"
  data={[
    { month: 'Jan', visitors: 1200 },
    { month: 'Feb', visitors: 1900 },
  ]}
  dataKey="month"
  series={[{ name: 'visitors', label: 'Visitors' }]}
  width={320}
  height={180}
/>


Theming​

The chart draws its grid, axes, text and reference lines from the same --bulma-chart-* CSS variables as every chart, with the same fallbacks to Bulma's tokens; see BarChart's Theming section. The line that marks the focused category takes the axis color, and the ring around each dot takes --bulma-chart-stroke-color, which falls back to --bulma-scheme-main, the page's background.


Accessibility​

  • The chart is a <figure> named by label, and the drawing is named by the same caption. description describes both.
  • A data table of every category and series renders beside the drawing, visually hidden with Bulma's is-sr-only, so a screen reader reads the numbers the areas show (WAI: complex images). Its first column is a row header, and a hidden series stays in it. It lists the values the data holds, so a stacked or percent chart's table reads the same as a default one's. showTable puts it on screen.
  • The drawing is a tab stop. Once it has focus, the left and right arrow keys move through the categories; the tooltip shows each one's values and a dot marks each area's point there (Recharts' keyboard layer).
  • Each legend entry is a button with aria-pressed. A hidden series' swatch is drawn hollow and its label greyed, so its state isn't told by color alone.
  • The swatches in the legend and tooltip are aria-hidden; each entry's text says which series it is.
  • Series colors are told apart by color alone in the drawing. When that matters, dash a series' edge with its strokeDasharray, write the values with showLabels, or keep the series few. A split chart's two colors repeat what the value axis already says, above or below zero, and a reference line at zero marks where they meet.

  • LineChart: The same rows and series, drawn as lines.
  • BarChart: The same rows and series, drawn as bars.
  • ComposedChart: Bars, lines and areas in one chart.
  • 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
seriesAreaChartSeries[]—Required. The series to draw, in order.
type'default' | 'stacked' | 'percent' | 'split''default'How the series share the chart. default draws each area from the axis, one over another, stacked one on another, and percent stacked to the same height, each a share of its category's total. split draws the first series alone, in one color above zero and another below it, from splitColors.
splitColors[ChartColor, ChartColor]['success', 'danger']The colors a split chart draws its series in: above zero, then below it. The series' own color isn't used.
curveType'linear' | 'monotone' | 'natural' | 'step' | 'stepBefore' | 'stepAfter' | 'bump''monotone'How every area's edge runs between its points, unless its series names its own.
hasDotsbooleanfalseDraws a dot on each point. The point under the pointer or keyboard focus is marked with a dot either way.
connectNullsbooleantrueDraws an area across a gap in the data, a row whose value is missing or null, rather than breaking it there.
strokeWidthnumber2How thick each area's edge is, in pixels.
fillOpacitynumber0.2How opaque each area's fill is, from 0 to 1. With hasGradient, it's the opacity the fade starts from.
hasGradientbooleantrueFades each area's fill from fillOpacity at its top to nothing at its bottom, or from its right to its left when the chart runs vertically, so an area of positive values is strongest along its edge and fades toward the axis. Without it, the fill is one flat color. A split chart always fills flat, in its two colors.
areaPropsPartial<Omit<AreaProps<ChartRow, unknown>, 'ref'>>—Props passed to every Recharts Area, after the chart's own, such as baseValue.
chartPropsPartial<React.ComponentProps<typeof RechartsAreaChart>>—Props passed to Recharts' AreaChart, after the chart's own, such as margin.
datareadonly ChartRow[]—Required. The rows to draw: one per category, with a key per series.
dataKeystring—Required. The key of data that holds each row's category, such as month.
orientation'horizontal' | 'vertical''horizontal'Which way the chart runs. vertical puts the categories down the side and the values across.
grid'horizontal' | 'vertical' | 'both' | 'none''horizontal'Which grid lines to draw.
gridPropsPartial<CartesianGridProps>—Props passed to Recharts' CartesianGrid, after the chart's own.
hasXAxisbooleantrueDraws the x axis.
hasYAxisbooleantrueDraws the y axis.
xAxisLabelstring—A title for the x axis.
yAxisLabelstring—A title for the y axis.
xAxisPropsPartial<XAxisProps>—Props passed to Recharts' XAxis, after the chart's own.
yAxisPropsPartial<YAxisProps>—Props passed to Recharts' YAxis, after the chart's own.
hasRightYAxisbooleanfalseDraws a second value axis on the right, for the series whose yAxisId is right. Ignored with orientation="vertical".
rightYAxisLabelstring—A title for the right y axis.
rightYAxisPropsPartial<YAxisProps>—Props passed to Recharts' YAxis for the right axis, after the chart's own.
referenceLines{ x?: string | number; y?: number; label?: string; color?: ChartColor }[]—Lines drawn across the chart at given values, such as a target.
showLabelsbooleanfalseWrites each value on the chart beside its mark.
tooltipPropsPartial<TooltipProps>—Props passed to Recharts' Tooltip, after the chart's own.
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.
valueFormatterChartValueFormatter—Writes each value on the axes, in the tooltip, on the labels and in the data table. Without one, values are written as useNumberFormat writes a number, in the LocaleProvider's locale.
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.
childrenReact.ReactNode—More Recharts elements to draw inside the chart, such as a Brush, a ReferenceArea, or <defs> for a pattern a color names with url(#id).
hasLegendbooleanfalseShows a legend. Each entry is a toggle button that hides or shows its series.
legendPosition'top' | 'bottom''bottom'Where the legend sits.
hiddenSeriesstring[]—The names of the series that are hidden, when you hold that state.
defaultHiddenSeriesstring[]—The names of the series hidden to begin with, when the chart holds it.
onHiddenSeriesChange(hiddenSeries: string[]) => void—Called with the names of the hidden series when the legend changes them.
refReact.Ref<HTMLElement>—Ref forwarded to the root <figure>.
...All standard HTML attributes and Bulma helper props—See Helper Props

Types:

  • AreaChartSeries: One series of an area chart: a line through its values, filled down to the axis. Its fields:
    • curveType: 'linear' | 'monotone' | 'natural' | 'step' | 'stepBefore' | 'stepAfter' | 'bump' — How this area's edge runs between its points. Defaults to the chart's curveType.
    • strokeDasharray: string — Draws this area's edge dashed, as an SVG stroke-dasharray such as 5 5: the length of each dash, then of each gap.
    • stackId: string — Areas with the same stackId stack one on another, so a default chart can stack some series and not others. With stacked and percent, a series without one stacks with the rest.
    • yAxisId: 'left' | 'right' — Which value axis it's drawn against. right needs hasRightYAxis; without it, and in a vertical chart, the series is drawn against the left axis. Default 'left'.
    • name: string — Required. The key of data that holds this series' values, and the name hiddenSeries holds. No two series share one.
    • label: string — What the legend, the tooltip and the data table call it. Defaults to name.
    • color: ChartColor — Its color. Without one, it takes the next of Bulma's palette colors.
  • 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.