[Chartjs]-Remove gap when updating ChartJS

3👍

Cool! After few hours of googling i have found that There is a open issue in chart js repo github absolutely related to this problem.Please take a look at it.

I have found some fixes. I didn’t try the second, but added a snippet for the first. Have a look at it!


Fix 1: Set the value of the first point to the second, then remove the second.

var CPUChart;
$(document).ready(function() {
  Chart.defaults.line.spanGaps = false;
  CPUChart = new Chart(cpu, {
    type: 'line',
    data: {
      datasets: [{
        label: "CPU Usage",
        backgroundColor: "rgba(51, 122, 183, 0.2)",
        borderColor: "#337AB7",
        data: [60, 62, 68, 61, 66, 70, 64, 67, 62, 63, 66, 60, 65, 62, 60, 89]
      }],
      labels: ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '']
    },
    options: {
      scales: {
        yAxes: [{
          ticks: {
            max: 100,
            min: 0
          }
        }]
      }
    }
  });

  setInterval(function() {
    var usage = Math.random() * (70 - 50) + 50;
    addData(CPUChart, '', parseInt(usage));
    removeData(CPUChart);
    $(cpuAmount).html(parseInt(usage) + '%');
  }, 1000);
});

function addData(chart, label, data) {
  chart.data.labels.push(label);
  chart.data.datasets.forEach((dataset) => {
    dataset.data.push(data);
  });
  chart.update();
}

function removeData(chart) {
  if (chart.data.datasets[0].data.length > 5) {
    chart.data.labels.shift();
    chart.data.datasets.forEach(dataset => {
      dataset.data[0] = dataset.data[1]
      dataset.data.splice(1, 1)
    })
    chart.update();
  }

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.js'></script>

<div style="height: 100%;width:100%">
  <canvas id="cpu" width="100%"></canvas>
  <span id="cpuAmount" style="font-weight: bold">Loading...</span>
</div>

Leave a comment