Search code examples
javascriptreactjstypescriptconfidence-intervalapexcharts

How to add confidence intervals for a line chart in (React) ApexCharts?


Using ApexCharts (more specifically, React-ApexCharts), how can I create a mean line plus a shaded region that visually shows the uncertainty of the estimate (e.g. quantiles, confidence intervals)?

The target output is similar to:


Solution

  • At the time of writing, ApexCharts doesn't offer this functionality out of the box. The following is a workaround inspired by this answer on GitHub from Phili230.

    Output

    Code

    const data = {
      labels: [
        "2022-01-01",
        "2022-02-01",
        "2022-03-01",
        "2022-04-01",
        "2022-05-01",
        "2022-06-01"
      ],
      mean: [14, 16, 18, 15, 19, 16],
      low: [11.5, 14, 15, 12.5, 17, 14.5],
      high: [15.6, 18, 20.5, 16.5, 21, 17]
    };
    export default function App() {
      const series = [
        {
          name: "95th quantile",
          type: "area",
          data: data.high
        },
        {
          name: "5th quantile",
          type: "area",
          data: data.low
        },
        {
          name: "mean",
          type: "line",
          data: data.mean
        }
      ];
      const options = {
        chart: {
          stacked: false
        },
        title: { text: "Mean estimate by month" },
        labels: data.labels,
        fill: {
          colors: ["#94ddf7", "#FFFFFF", "#FFFFFF"],
          opacity: [0.5, 1.0, 1.0],
          type: "solid"
        },
        stroke: {
          show: true,
          colors: ["#94ddf7", "#94ddf7", "#0674fe"],
          width: [2, 2, 5]
        },
        xaxis: {
          type: "datetime"
        },
        grid: {
          strokeDashArray: 0,
          position: "front"
        },
        legend: { show: false },
        tooltip: { inverseOrder: true },
        yaxis: {
          min: 0,
          title: {
            text: "Mean estimate"
          }
        }
      };
    
      return (
        <Chart
          options={options}
          series={series}
          type="line"
          width={"100%"}
          height={"500px"}
        />
      );
    }
    

    CodeSandbox

    https://codesandbox.io/s/serene-benji-w34gz3

    Remarks

    • The order in which the series are defined is important, as the background brought by the "low" bar must on top of that brought by the "high" bar
    • The grid also has to be brought to the front
    • An undesired side-effect is that the grid is above the mean, low and high lines