简体   繁体   中英

How to use chartjs-plugin-trendline with react-chartjs-2

I want to add 'Trend' line to my line chart. I am using react-chartjs-2 to draw charts on my website. The code looks like:

import { Line } from 'react-chartjs-2';
import trendlineLinear from 'chartjs-plugin-trendline';

const PatientInfectionChart = ({ data, labels }) => {
  const datasets = [
    {
      data: data.totalInfected,
      backgroundColor: 'rgb(233, 85, 0)',
      borderColor: 'rgba(233, 85, 0, 0.7)',
      label: 'Today Infected',
    },
    {
      data: data.todayRecovered,
      backgroundColor: 'rgb(23, 198, 113)',
      borderColor: 'rgba(23, 198, 113, 0.7)',
      label: 'Today Recovered',
      trendlineLinear: {
        style: 'rgb(23, 198, 113)',
        lineStyle: 'dotted',
        width: 2,
      },
    },
  ];
  return (
    <Line
      data={{ datasets, labels }}
      plugins={[trendlineLinear]}
      options={{
        maintainAspectRatio: false,
        scales: {
          y: {
            beginAtZero: true,
          },
        },
      }}
    />
  );
};

export default PatientInfectionChart;

However, I get the following error:

Uncaught TypeError: Cannot read property 'ctx' of undefined
    at Object.afterDraw (chartjs-plugin-trendline.js:23)
    at callback (helpers.segment.js:89)
    at PluginService._notify (chart.esm.js:4737)
    at PluginService.notify (chart.esm.js:4724)
    at Chart.notifyPlugins (chart.esm.js:5788)
    at Chart.draw (chart.esm.js:5537)
    at chart.esm.js:66
    at Map.forEach (<anonymous>)
    at Animator._update (chart.esm.js:44)
    at chart.esm.js:34

How to I fix this?

The trendline plugin requires chart.js version 2, react chart.js uses version 3 so you will need to downgrade react-chartjs

Commands:

yarn remove react-chartjs-2

yarn add react-chartjs-2@2.11.2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM