如何减少react-chart-js2中显示的数据点数(数据抽取)

时间:2019-05-28 14:02:57

标签: javascript reactjs chart.js

我正在使用react-chartjs-2绘制带有给定时间段内价格数据的折线图(例如,过去一周,过去一个月的价格,年初至今等)。当显示超过60天左右的价格数据时,该行开始变得混乱。因此,我想减少在图表上显示的数据点的数量,同时仍然代表整个数据范围。

我遇到了插件chartjs-pluging-downsample,看来它应该可以工作: https://www.npmjs.com/package/chartjs-plugin-downsample

react-chartjs-2文档也描述了一种扩展图表的方法,但我一直无法弄清楚插件代码

import { Chart } from 'react-chartjs-2';

componentWillMount() {
  Chart.pluginService.register({
    afterDraw: function (chart, easing) {
      // Plugin code.
    }
  });
}
import { Line } from 'react-chartjs-2';
import 'chartjs-plugin-downsample';

<Line
  ref={(reference) => this.chartReference = reference }
  options={{
    responsive: true,
    downsample: {
    enabled: true,
    threshold: 50,
    auto: false, // don't re-downsample the data every move
    onInit: true, // but do resample it when we init the chart (this is default)

    preferOriginalData: true, // use our original data when downscaling so we can downscale less, if we need to.
    restoreOriginalData: false, // if auto is false and this is true, original data will be restored on pan/zoom - that isn't what we want.
    }
  }}
  data={this.makeChart}
/>

如何使用此插件(或其他方法)获得所需的结果?

1 个答案:

答案 0 :(得分:1)

好吧,我想我已经弄清楚了,它非常简单,我打印了从chartjs-plugin-downsample导入的对象,它看起来可疑地像您要传递给插件服务的东西。

因此,执行此操作的方法是:

import { Chart } from 'react-chartjs-2';
import DownsamplePlugin from 'chartjs-plugin-downsample';

...(component declaration)...

componentWillMount() {
  Chart.plugins.register(DownsamplePlugin);
}

...(rest of your component)...

,然后随便播放选项。确保设置您的minmax选项,否则我会做一些奇怪的事情。