chart.js load totally new data

前端 未结 20 1238
有刺的猬
有刺的猬 2020-11-28 21:12

The API for chart.js allows one to edit points of the datasets loaded into it, for example:

.update( )

Calling update() on

相关标签:
20条回答
  • 2020-11-28 21:46

    ChartJS 2.6 supports data reference replacement (see Note in update(config) documentation). So when you have your Chart, you could basically just do this:

    myChart.data.labels = ['1am', '2am', '3am', '4am'];
    myChart.data.datasets[0].data = [0, 12, 35, 36];
    myChart.update();
    

    It doesn't do the animation you'd get from adding points, but existing points on the graph will be animated.

    0 讨论(0)
  • 2020-11-28 21:46

    If anyone is looking for how to do this in React. For a linechart, assuming you have a wrapper component around the chart:

    (This assumes you are using v2. You do not need to use react-chartjs. This is using the normal chart.js package from npm.)

    propTypes: {
      data: React.PropTypes.shape({
        datasets: React.PropTypes.arrayOf(
          React.PropTypes.shape({
    
          })
        ),
        labels: React.PropTypes.array.isRequired
      }).isRequired
    },
    componentDidMount () {
      let chartCanvas = this.refs.chart;
    
      let myChart = new Chart(chartCanvas, {
        type: 'line',
        data: this.props.data,
        options: {
          ...
        }
      });
    
      this.setState({chart: myChart});
    },
    componentDidUpdate () {
        let chart = this.state.chart;
        let data = this.props.data;
    
        data.datasets.forEach((dataset, i) => chart.data.datasets[i].data = dataset.data);
    
        chart.data.labels = data.labels;
        chart.update();
    },
    render () {
      return (
        <canvas ref={'chart'} height={'400'} width={'600'}></canvas>
      );
    }
    

    The componentDidUpdate functionality allows you to update, add, or remove any data from the this.props.data.

    0 讨论(0)
提交回复
热议问题