0👍
✅
The problem in your addData
function is that labels
and data
gets out of sync. While you keep data to a fixed length
of 10 using Array.shift()
, labels is steadily growing. This can be easily fixed if you also keep the labels
to a fixed length
of 10.
let index = config.data.datasets[0].data.length;
function addData(a) {
config.data.labels.push('Data ' + ++index);
config.data.datasets.forEach(dataset => dataset.data.push(a));
if (config.data.datasets[0].data.length > 10) {
config.data.labels.shift();
config.data.datasets[0].data.shift();
}
myLineChart.update();
}
Please have a look at the following runnable code sample. Keep pressing the Add Value button too see what happens.
var ctx = document.getElementById('myChart').getContext('2d');
var config = {
type: 'line',
data: {
labels: ['Data 1','Data 2','Data 3','Data 4','Data 5','Data 6','Data 7','Data 8','Data 9','Data 10'],
datasets: [{
label: 'CPU Allocation of all cores',
data: [0,0,0,0,0,0,0,0,0,0],
borderColor: [
'#61559a',
'#61559a',
'#61559a',
'#61559a',
'#61559a',
'#61559a',
'#61559a',
'#61559a',
'#61559a',
'#61559a'
],
borderWidth: 1
}]
},
options: {
scaleOverride : true,
scaleSteps : 10,
scaleStepWidth : 10,
scaleStartValue : 0,
responsive: true,
title: {
display: false
},
tooltips: {
mode: 'index',
intersect: false,
},
hover: {
mode: 'nearest',
intersect: true
},
scales: {
xAxes: [{
display: false
}],
yAxes: [{
ticks: {
suggestedMin: 0,
suggestedMax: 100,
stepSize: 10,
beginAtZero: true
},
display: true,
scaleLabel: {
display: true,
labelString: 'Percent'
}
}]
}
}
}
var myLineChart = new Chart(ctx, config);
let index = config.data.datasets[0].data.length;
function addData(a) {
config.data.labels.push('Data ' + ++index);
config.data.datasets.forEach(dataset => dataset.data.push(a));
if (config.data.datasets[0].data.length > 10) {
config.data.labels.shift();
config.data.datasets[0].data.shift();
}
myLineChart.update();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<button onClick="addData(Math.floor(Math.random() * (100 + 1)))">Add Value</button>
<canvas id="myChart" height="80"></canvas>
Source:stackexchange.com