ChartJS,添加新数据集

时间:2016-03-16 21:02:41

标签: javascript jquery chart.js

我想知道如何显示我的3条曲线如下:首先是第一条,在5000间隔之后,添加第二条,再在5000之后,添加第三条数据集。

下面的代码更新了第二个数据集中的一个点,但我想要的是添加一个完整的数据集。

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
  <script src="http://www.chartjs.org/assets/Chart.min.js"></script>
</head>
<body>
  <canvas id="updating-chart" width="500" height="300"></canvas>
 <script>
 var canvas = document.getElementById('updating-chart'),
    ctx = canvas.getContext('2d'),
    startingData = {
      labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
      datasets: [

          {    //first dataset
              fillColor: "rgba(151,187,205,0.2)",
              strokeColor: "rgba(151,187,205,1)",
              pointColor: "rgba(151,187,205,1)",
              pointStrokeColor: "#fff",
              data: [69.23077, 78.18182, 66.66667, 65.45455, 38.18182, 40.35088, 45.61404, 36.53846, 43.28358, 54.54545, 31.25000, 44.73684]
          }
          ,
           {  // Second dataset
              fillColor: "rgba(220,220,220,0.2)",
              strokeColor: "rgba(220,220,220,1)",
              pointColor: "rgba(220,220,220,1)",
              pointStrokeColor: "#fff",
              data: [25.00000, 12.72727, 22.22222, 18.18182, 54.54545, 40.35088, 45.61404, 42.30769, 31.34328, 21.81818, 34.37500, 36.84211]
          },
          {   // third dataset
              fillColor: "rgba(151,187,205,0.2)",
              strokeColor: "rgba(151,187,205,1)",
              pointColor: "rgba(151,187,205,1)",
              pointStrokeColor: "#fff",
              data: [1.923077, 3.636364, 4.444444, 5.454545, 0.000000, 5.263158, 3.508772, 9.615385, 16.417910, 18.181818, 34.375000, 15.789474]
          }


      ]
    };

// Reduce the animation steps for demo clarity.
var myLiveChart = new Chart(ctx).Line(startingData, {animationSteps: 15});


setInterval(function(){

  // Update one of the points in the second dataset
  myLiveChart.datasets[1].points[1].value =  Math.random();


  myLiveChart.update();
}, 5000);




 </script>
</body>
</html>

怎么做?

1 个答案:

答案 0 :(得分:1)

首先将除第一个数组之外的每个数组设置为空白。然后使用onAnimationComplete逐步加载它们。

改编自https://stackoverflow.com/a/36010562/360067

...

var dataArrays = [];
for (var i = 1; i < data.datasets.length; i++) {
    dataArrays.push(data.datasets[i].data);
    data.datasets[i].data = data.datasets[i].data.map(function() {
        return 0
    });
}    

var myLineChart = new Chart(ctx).Line(data, {
  animationEasing: 'linear',
  onAnimationComplete: function () {
    if (dataArrays.length !== 0) {
      var index = myLineChart.datasets.length - dataArrays.length;
      myLineChart.datasets[index].points.forEach(function (point, i) {
        point.value = dataArrays[0][i];
      });
      myLineChart.update();
      dataArrays.shift();
    }
  }
});

小提琴 - http://jsfiddle.net/ngf79suk/