Skip to main content

LineChart

Overview​

The LineChart component draws values as lines across the categories, one line per series, to show how they change.

It wraps Recharts' LineChart 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 { LineChart } 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 visitors = [
    { month: 'Jan', desktop: 1860, mobile: 800 },
    { month: 'Feb', desktop: 3050, mobile: 2000 },
    { month: 'Mar', desktop: 2370, mobile: 1200 },
    { month: 'Apr', desktop: 730, mobile: 1900 },
    { month: 'May', desktop: 2090, mobile: 1300 },
  ];

  return (
    <LineChart
      label="Monthly visitors"
      data={visitors}
      dataKey="month"
      series={[
        { name: 'desktop', label: 'Desktop', color: 'primary' },
        { name: 'mobile', label: 'Mobile', color: 'info' },
      ]}
      hasLegend
    />
  );
}

Curves​

curveType sets how the lines run between their points: monotone (the default) curves them without overshooting a point, linear draws them straight, natural and bump bend them more freely, and step, stepBefore and stepAfter draw steps. A series' own curveType wins over the chart's.

function example() {
  const plans = [
    { month: 'Jan', basic: 120, pro: 40 },
    { month: 'Feb', basic: 135, pro: 52 },
    { month: 'Mar', basic: 128, pro: 61 },
    { month: 'Apr', basic: 150, pro: 75 },
    { month: 'May', basic: 162, pro: 80 },
  ];

  return (
    <LineChart
      label="Subscribers by plan"
      curveType="linear"
      data={plans}
      dataKey="month"
      series={[
        { name: 'basic', label: 'Basic', color: 'link' },
        { name: 'pro', label: 'Pro', color: 'success', curveType: 'step' },
      ]}
      hasLegend
    />
  );
}

Dashed Series​

A series' strokeDasharray draws its line dashed, such as a forecast beside the actual values, which tells the two apart by more than their color.

function example() {
  const revenue = [
    { month: 'Jul', actual: 4200, forecast: null },
    { month: 'Aug', actual: 4600, forecast: null },
    { month: 'Sep', actual: 5100, forecast: 5100 },
    { month: 'Oct', actual: null, forecast: 5500 },
    { month: 'Nov', actual: null, forecast: 5800 },
  ];

  return (
    <LineChart
      label="Revenue and forecast"
      data={revenue}
      dataKey="month"
      series={[
        { name: 'actual', label: 'Actual', color: 'primary' },
        {
          name: 'forecast',
          label: 'Forecast',
          color: 'primary',
          strokeDasharray: '6 4',
        },
      ]}
      connectNulls={false}
      hasLegend
    />
  );
}

Dots, Gaps and Thickness​

Each point gets a dot; hasDots={false} leaves them off, and the point under the pointer or the keyboard focus is marked either way. A line runs across a gap in the data (a missing or null value) unless connectNulls={false} breaks it there. strokeWidth sets how thick the lines are.

function example() {
  const readings = [
    { hour: '08:00', temperature: 14 },
    { hour: '09:00', temperature: 16 },
    { hour: '10:00', temperature: null },
    { hour: '11:00', temperature: 21 },
    { hour: '12:00', temperature: 23 },
  ];

  return (
    <Columns>
      <Column>
        <LineChart
          label="Temperature, gap connected"
          showLabel
          data={readings}
          dataKey="hour"
          series={[
            { name: 'temperature', label: 'Temperature', color: 'danger' },
          ]}
          unit=" °C"
          height={220}
        />
      </Column>
      <Column>
        <LineChart
          label="Temperature, gap broken"
          showLabel
          data={readings}
          dataKey="hour"
          series={[
            { name: 'temperature', label: 'Temperature', color: 'danger' },
          ]}
          unit=" °C"
          connectNulls={false}
          hasDots={false}
          strokeWidth={4}
          height={220}
        />
      </Column>
    </Columns>
  );
}

Vertical​

orientation="vertical" lays the categories down the side, with the values running across, the way a profile by depth or height reads.

function example() {
  const ocean = [
    { depth: '0 m', temperature: 24 },
    { depth: '50 m', temperature: 22 },
    { depth: '100 m', temperature: 17 },
    { depth: '200 m', temperature: 11 },
    { depth: '500 m', temperature: 7 },
  ];

  return (
    <LineChart
      label="Water temperature by depth"
      orientation="vertical"
      grid="vertical"
      data={ocean}
      dataKey="depth"
      series={[{ name: 'temperature', label: 'Temperature', color: 'info' }]}
      unit=" °C"
      showLabels
      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.

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 (
    <LineChart
      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', visitors: 9800, conversion: 2.1 },
    { month: 'Feb', visitors: 12500, conversion: 2.6 },
    { month: 'Mar', visitors: 11100, conversion: 2.4 },
    { month: 'Apr', visitors: 8900, conversion: 1.8 },
  ];

  return (
    <LineChart
      label="Visitors and conversion"
      data={shop}
      dataKey="month"
      series={[
        { name: 'visitors', label: 'Visitors', color: 'primary' },
        {
          name: 'conversion',
          label: 'Conversion',
          color: 'success',
          yAxisId: 'right',
        },
      ]}
      hasRightYAxis
      yAxisLabel="Visitors"
      rightYAxisLabel="Conversion (%)"
      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 signups = [
    { week: 'W1', signups: 120 },
    { week: 'W2', signups: 180 },
    { week: 'W3', signups: 240 },
    { week: 'W4', signups: 210 },
    { week: 'W5', signups: 290 },
  ];

  return (
    <LineChart
      label="Weekly sign-ups"
      data={signups}
      dataKey="week"
      series={[{ name: 'signups', label: 'Sign-ups', color: 'primary' }]}
      referenceLines={[
        { y: 200, label: 'Goal', color: 'success' },
        { x: 'W3', label: 'Launch' },
      ]}
    />
  );
}

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 visitors = [
    { month: 'Jan', desktop: 1860, mobile: 800, tablet: 420 },
    { month: 'Feb', desktop: 3050, mobile: 2000, tablet: 610 },
    { month: 'Mar', desktop: 2370, mobile: 1200, tablet: 580 },
    { month: 'Apr', desktop: 730, mobile: 1900, tablet: 690 },
  ];
  const [hidden, setHidden] = useState(['tablet']);

  return (
    <>
      <Buttons mb="3">
        <Button size="small" onClick={() => setHidden([])}>
          Show all
        </Button>
      </Buttons>
      <LineChart
        label="Monthly visitors"
        data={visitors}
        dataKey="month"
        series={[
          { name: 'desktop', label: 'Desktop', color: 'primary' },
          { name: 'mobile', label: 'Mobile', color: 'info' },
          { name: 'tablet', label: 'Tablet', 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 price = [
    { day: 'Mon', price: 182.4 },
    { day: 'Tue', price: 185.1 },
    { day: 'Wed', price: 179.9 },
    { day: 'Thu', price: 188.3 },
    { day: 'Fri', price: 191.7 },
  ];
  const dollars = new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD',
  });

  return (
    <LineChart
      label="Closing price"
      data={price}
      dataKey="day"
      series={[{ name: 'price', label: 'Price', color: 'success' }]}
      valueFormatter={value => dollars.format(value)}
      yAxisProps={{ domain: ['dataMin - 5', 'dataMax + 5'] }}
      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 = [
    { round: '1', red: 30, blue: 20, green: 25 },
    { round: '2', red: 45, blue: 38, green: 30 },
    { round: '3', red: 52, blue: 60, green: 41 },
    { round: '4', red: 70, blue: 66, green: 58 },
  ];

  return (
    <LineChart
      label="Scores by round"
      data={scores}
      dataKey="round"
      series={[
        { name: 'red', label: 'Red', color: 'danger-40' },
        { name: 'blue', label: 'Blue', color: 'link-60' },
        { name: 'green', label: 'Green', color: '#2a9d8f' },
      ]}
      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 visitors = [
    { month: 'Jan', desktop: 1860, mobile: 800 },
    { month: 'Feb', desktop: 3050, mobile: 2000 },
    { month: 'Mar', desktop: 2370, mobile: 1200 },
  ];

  return (
    <LineChart
      label="Monthly visitors"
      showLabel
      showTable
      data={visitors}
      dataKey="month"
      series={[
        { name: 'desktop', label: 'Desktop' },
        { name: 'mobile', label: 'Mobile' },
      ]}
      height={200}
    />
  );
}

Recharts Props and Children​

Each Recharts part the chart draws takes its own props after the chart's: lineProps for every Line, chartProps for Recharts' LineChart, and xAxisProps, yAxisProps, rightYAxisProps and tooltipProps. children adds more Recharts elements, such as a ReferenceArea or a Brush.

function example() {
  const visitors = [
    { month: 'Jan', visitors: 1860 },
    { month: 'Feb', visitors: 3050 },
    { month: 'Mar', visitors: 2370 },
    { month: 'Apr', visitors: 2730 },
  ];

  return (
    <LineChart
      label="Monthly visitors"
      data={visitors}
      dataKey="month"
      series={[{ name: 'visitors', label: 'Visitors', color: 'link' }]}
      lineProps={{ strokeLinecap: 'round' }}
      chartProps={{ margin: { top: 24, right: 24, bottom: 0, left: 0 } }}
      strokeWidth={4}
    />
  );
}

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.

<LineChart
  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 lines show (WAI: complex images). Its first column is a row header, and a hidden series stays in it. 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 larger dot marks each line'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 with its strokeDasharray, write the values with showLabels, or keep the series few.

  • BarChart: The same rows and series, drawn as bars.
  • AreaChart: The same rows and series, drawn as filled areas.
  • 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
seriesLineChartSeries[]—Required. The series to draw, in order.
curveType'linear' | 'monotone' | 'natural' | 'step' | 'stepBefore' | 'stepAfter' | 'bump''monotone'How every line runs between its points, unless its series names its own.
hasDotsbooleantrueDraws a dot on each point. The point under the pointer or keyboard focus is marked with a larger dot either way.
connectNullsbooleantrueDraws a line across a gap in the data, a row whose value is missing or null, rather than breaking it there.
strokeWidthnumber2How thick each line is, in pixels.
linePropsPartial<Omit<LineProps, 'ref'>>—Props passed to every Recharts Line, after the chart's own, such as dot.
chartPropsPartial<React.ComponentProps<typeof RechartsLineChart>>—Props passed to Recharts' LineChart, 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:

  • 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.
  • LineChartSeries: One series of a line chart: a line through its values. Its fields:
    • curveType: 'linear' | 'monotone' | 'natural' | 'step' | 'stepBefore' | 'stepAfter' | 'bump' — How this line runs between its points. Defaults to the chart's curveType.
    • strokeDasharray: string — Draws this line dashed, as an SVG stroke-dasharray such as 5 5: the length of each dash, then of each gap. A dashed line tells a series apart by more than its color, such as a forecast beside the actuals.
    • 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.