我想用Chartjs显示一个图表,该图表显示实时数据并沿x轴缓慢滚动,我在这里用js小提琴尝试了一下,它像疯了似的跳来跳去:https://jsfiddle.net/rsnufpq7/

图表应仅移至左侧,旧点不在视野中,而没有此动画,如此处的第二个示例所示:https://bost.ocks.org/mike/path/

var canvas = document.getElementById('myChart');
var data = {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [
        {
            label: "My First dataset",
            fill: false,
            lineTension: 0.0,
            backgroundColor: "rgba(75,192,192,0.4)",
            borderColor: "rgba(75,192,192,1)",
            borderCapStyle: 'butt',
            borderDash: [],
            borderDashOffset: 0.0,
            borderJoinStyle: 'miter',
            pointBorderColor: "rgba(75,192,192,1)",
            pointBackgroundColor: "#fff",
            pointBorderWidth: 1,
            pointHoverRadius: 5,
            pointHoverBackgroundColor: "rgba(75,192,192,1)",
            pointHoverBorderColor: "rgba(220,220,220,1)",
            pointHoverBorderWidth: 2,
            pointRadius: 5,
            pointHitRadius: 10,
            data: [65, 59, 80, 0, 56, 55, 40],
        }
    ]
};

var zero = 7;
function adddata(){

   var value = Math.floor((Math.random() * 10) + 1);;
      myLineChart.data.labels.push(zero);
      myLineChart.data.labels.splice(0, 1);
  myLineChart.data.datasets[0].data.splice(0, 1);
  myLineChart.data.datasets[0].data.push(value);


  myLineChart.update();
  zero++;
}



   setInterval(function(){
   adddata();
    },1000);

var option = {
    showLines: true
};
var myLineChart = Chart.Line(canvas,{
    data:data,
  options:option
});

最佳答案

您的代码按预期方式工作,唯一缺少的是y轴未定义范围,并且正在动态调整。

为了实现这一目标,我将您的选择范围扩展为如下所示。

var option = {
  showLines: true,
  scales: {
    yAxes: [{
      display: true,
      ticks: {
        beginAtZero:true,
        min: 0,
        max: 100
      }
    }]
  }
};


我已经定义了y轴的最小值和最大值,并且它不再跳跃了。

这是工作中的fiddle

关于javascript - Chartjs实时图形x轴移动,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45664149/

10-12 06:31