Chartjs-Update Chart JS data dynamically and add new data, remove old data to create timeline "like" chart

2👍

you can use chart.update() method with assigning a new dataset

<canvas id="myChart" width="400" height="250"></canvas>
<input type="button" value="New Data" onclick="RandomData()">


var canvas = document.getElementById('myChart');
var data = {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [
        {
            label: "My dataset",
            fill: false,
            lineTension: 0.1,
            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],
        }
    ]
};

function RandomData(){
  var newData=[];
  for(var i=0;i<7;i++){
     newData.push(Math.round(Math.random() * 100))
  }
    myLineChart.data.datasets[0].data =newData;
  myLineChart.update();
}
var option = {
    showLines: true
};
var myLineChart = Chart.Line(canvas,{
    data:data,
  options:option
});

please see a demo here

Leave a comment