Skip to main content

BarChart

Overview​

The BarChart component draws values as bars, one group per category, side by side, stacked, as shares of a whole or as a waterfall.

It wraps Recharts' BarChart 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 { BarChart } 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 sales = [
    { month: 'Jan', online: 1200, retail: 900 },
    { month: 'Feb', online: 1900, retail: 1200 },
    { month: 'Mar', online: 400, retail: 1000 },
    { month: 'Apr', online: 1000, retail: 200 },
  ];

  return (
    <BarChart
      label="Monthly sales"
      data={sales}
      dataKey="month"
      series={[
        { name: 'online', label: 'Online', color: 'primary' },
        { name: 'retail', label: 'Retail', color: 'info' },
      ]}
      hasLegend
    />
  );
}

Stacked and Percent​

type="stacked" stacks the series in one bar per category. type="percent" stacks them to the same height, so each bar shows its category's split, and the value axis reads in percent. The tooltip and the data table still show the values the data holds.

function example() {
  const sales = [
    { month: 'Jan', online: 1200, retail: 900, wholesale: 400 },
    { month: 'Feb', online: 1900, retail: 1200, wholesale: 500 },
    { month: 'Mar', online: 400, retail: 1000, wholesale: 700 },
  ];
  const series = [
    { name: 'online', label: 'Online', color: 'primary' },
    { name: 'retail', label: 'Retail', color: 'info' },
    { name: 'wholesale', label: 'Wholesale', color: 'warning' },
  ];

  return (
    <Columns>
      <Column>
        <BarChart
          label="Sales, stacked"
          showLabel
          type="stacked"
          data={sales}
          dataKey="month"
          series={series}
          height={240}
        />
      </Column>
      <Column>
        <BarChart
          label="Sales, as shares"
          showLabel
          type="percent"
          data={sales}
          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.

Waterfall​

type="waterfall" draws the first series as steps, each bar starting where the last one ended, the way a cash flow or a budget runs. A row with standalone: true starts from zero instead, for an opening or closing total, and a row's own color key colors its bar. The tooltip and the data table give each step's running total beside it, under the heading labels.total names.

function example() {
  const cashFlow = [
    { item: 'Opening', amount: 1000, standalone: true },
    { item: 'Sales', amount: 600 },
    { item: 'Services', amount: 250 },
    { item: 'Payroll', amount: -700, color: 'danger' },
    { item: 'Closing', amount: 1150, standalone: true, color: 'success' },
  ];

  return (
    <BarChart
      label="Cash flow"
      type="waterfall"
      data={cashFlow}
      dataKey="item"
      series={[{ name: 'amount', label: 'Amount', color: 'info' }]}
      showLabels
    />
  );
}

Vertical​

orientation="vertical" lays the categories down the side, which suits long category names.

function example() {
  const languages = [
    { name: 'TypeScript', repos: 820 },
    { name: 'JavaScript', repos: 760 },
    { name: 'Python', repos: 640 },
    { name: 'Go', repos: 310 },
  ];

  return (
    <BarChart
      label="Repositories by language"
      orientation="vertical"
      grid="vertical"
      data={languages}
      dataKey="name"
      series={[{ name: 'repos', label: 'Repositories', color: 'link' }]}
      showLabels
      height={240}
    />
  );
}

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 beside its bar.

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 (
    <BarChart
      label="Visits per day"
      data={visits}
      dataKey="day"
      series={[{ name: 'visits', label: 'Visits', color: 'success' }]}
      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 shop = [
    { month: 'Jan', orders: 120, revenue: 9800 },
    { month: 'Feb', orders: 150, revenue: 12500 },
    { month: 'Mar', orders: 90, revenue: 7100 },
  ];

  return (
    <BarChart
      label="Orders and revenue"
      data={shop}
      dataKey="month"
      series={[
        { name: 'orders', label: 'Orders', color: 'primary' },
        {
          name: 'revenue',
          label: 'Revenue',
          color: 'warning',
          yAxisId: 'right',
        },
      ]}
      hasRightYAxis
      yAxisLabel="Orders"
      rightYAxisLabel="Revenue"
      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 sales = [
    { month: 'Jan', sales: 1200 },
    { month: 'Feb', sales: 1900 },
    { month: 'Mar', sales: 1400 },
    { month: 'Apr', sales: 1700 },
  ];

  return (
    <BarChart
      label="Sales against target"
      data={sales}
      dataKey="month"
      series={[{ name: 'sales', label: 'Sales', color: 'primary' }]}
      referenceLines={[{ y: 1500, label: 'Target', 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 sales = [
    { month: 'Jan', online: 1200, retail: 900, wholesale: 400 },
    { month: 'Feb', online: 1900, retail: 1200, wholesale: 500 },
    { month: 'Mar', online: 400, retail: 1000, wholesale: 700 },
  ];
  const [hidden, setHidden] = useState(['wholesale']);

  return (
    <>
      <Buttons mb="3">
        <Button size="small" onClick={() => setHidden([])}>
          Show all
        </Button>
      </Buttons>
      <BarChart
        label="Monthly sales"
        data={sales}
        dataKey="month"
        series={[
          { name: 'online', label: 'Online', color: 'primary' },
          { name: 'retail', label: 'Retail', color: 'info' },
          { name: 'wholesale', label: 'Wholesale', 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 },
  ];
  const dollars = new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD',
    maximumFractionDigits: 0,
  });

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

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 scores = [
    { team: 'Red', low: 30, mid: 50, high: 20 },
    { team: 'Blue', low: 20, mid: 45, high: 35 },
  ];

  return (
    <BarChart
      label="Score bands by team"
      type="stacked"
      data={scores}
      dataKey="team"
      series={[
        { name: 'low', label: 'Low', color: 'primary-30' },
        { name: 'mid', label: 'Mid', color: 'primary-50' },
        { name: 'high', label: 'High', color: 'primary-70' },
      ]}
      hasLegend
      height={220}
    />
  );
}

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 sales = [
    { month: 'Jan', online: 1200, retail: 900 },
    { month: 'Feb', online: 1900, retail: 1200 },
  ];

  return (
    <BarChart
      label="Monthly sales"
      showLabel
      showTable
      data={sales}
      dataKey="month"
      series={[
        { name: 'online', label: 'Online' },
        { name: 'retail', label: 'Retail' },
      ]}
      height={200}
    />
  );
}

Recharts Props and Children​

Each Recharts part the chart draws takes its own props after the chart's: barProps for every Bar (here, rounded tops), chartProps for Recharts' BarChart, 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 sales = [
    { month: 'Jan', sales: 1200 },
    { month: 'Feb', sales: 1900 },
    { month: 'Mar', sales: 1400 },
  ];

  return (
    <BarChart
      label="Monthly sales"
      data={sales}
      dataKey="month"
      series={[{ name: 'sales', label: 'Sales', color: 'url(#sales-stripes)' }]}
      barProps={{ radius: [6, 6, 0, 0] }}
      chartProps={{ barCategoryGap: '30%' }}
    >
      <defs>
        <pattern
          id="sales-stripes"
          width="8"
          height="8"
          patternUnits="userSpaceOnUse"
          patternTransform="rotate(45)"
        >
          <rect width="8" height="8" fill="var(--bulma-link)" />
          <line
            x1="0"
            y1="0"
            x2="0"
            y2="8"
            stroke="var(--bulma-scheme-main)"
            strokeWidth="3"
          />
        </pattern>
      </defs>
    </BarChart>
  );
}

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. Recharts draws in the browser, so a server render holds the chart's caption, legend and data table, and the drawing appears once the page hydrates.

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


Theming​

The chart draws its own lines and text from CSS variables that fall back to Bulma's tokens, so it follows Theme and dark mode with nothing set. Set them in your stylesheet to change them:

:root {
--bulma-chart-grid-color: var(--bulma-border); /* grid lines */
--bulma-chart-axis-color: var(--bulma-border); /* axis lines */
--bulma-chart-text-color: var(--bulma-text-weak); /* ticks and axis titles */
--bulma-chart-cursor-color: var(
--bulma-background
); /* the hovered category */
--bulma-chart-reference-color: var(--bulma-text); /* reference lines */
}

The legend is a row of Bulma button is-ghost toggles, the tooltip a Bulma box and the data table a Bulma table, so they take your Bulma styling as they are. The package ships no stylesheet of its own.


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, rather than a <title>, which a browser would show as a tooltip over the whole drawing.
  • 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 bars show (WAI: complex images). Its first column is a row header. A waterfall's table adds the running total each bar reaches. 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 and the tooltip shows each one's values (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, write the values on the bars with showLabels, or tell series apart with a pattern fill (see Recharts Props and Children).

  • Table: The Bulma table the chart's data table is drawn with.
  • RingProgress: One value, or a few, drawn as a ring.
  • Progress: One value drawn as a bar.
  • LocaleProvider: The locale the chart writes its numbers in.
  • Helper Props: Bulma helper props for spacing, color, etc.

Additional Resources​


Props​

PropTypeDefaultDescription
seriesBarChartSeries[]—Required. The series to draw, in order.
type'default' | 'stacked' | 'percent' | 'waterfall''default'How the series share a category. default draws them side by side, stacked one on another, and percent stacked to the same height, each bar a share of its category's total. waterfall draws the first series as steps, each bar starting where the last ended; a row with standalone: true starts from zero instead, for a total, and a row's own color key colors its bar.
barPropsPartial<Omit<BarProps, 'ref'>>—Props passed to every Recharts Bar, after the chart's own, such as radius.
labels{ total?: string }—The data table's and tooltip's words for a waterfall's running total, for a page in another language.
chartPropsPartial<React.ComponentProps<typeof RechartsBarChart>>—Props passed to Recharts' BarChart, after the chart's own, such as barGap.
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:

  • BarChartSeries: One series of bars. Its fields:
    • stackId: string — Bars with the same stackId stack into one bar per category, 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.