0👍
✅
Each time, a new value is available, add it to dataset.data
. As soon as a certain limit of values is reached, remove the oldest value through Array.shift()
. Once dataset.data
is updated, you need to invoke chart.update()
.
Please take a look at below runnable code and see how it works. Note that this code simulates the API using setInterval()
.
var chart = new Chart('chart', {
type: 'line',
data: {
datasets: [{
data: [],
fill: false,
lineTension: 0.1,
borderColor: 'black',
pointRadius: 0
}]
},
options: {
plugins: {
legend: {
display: false
},
tooltip: {
enabled: false
}
},
scales: {
x: {
type: 'time',
time: {
unit: 'second',
displayFormats: {
second: 'h:m:s a'
}
},
grid: {
display: false,
drawBorder: false
},
ticks: {
maxTicksLimit: 3,
maxRotation: 0
}
},
y: {
min: 0,
max: 10,
ticks: {
stepSize: 2
}
}
}
}
});
var maxValues = 20;
setInterval(() => {
const data = chart.data.datasets[0].data;
const v = Math.floor((Math.random() * 9) + 1);
if (data.length >= maxValues) {
data.shift();
}
data.push({ x: new Date(), y: v });
chart.update();
}, 300);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment-with-locales.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment@1.0.0"></script>
<canvas id="chart" height="80"></canvas>
Source:stackexchange.com