Reputation: 151
I'm in a project that need show only the last 100 samples on chart.js. For now, I have this:
I'm using node and mongo, my query gives the last 100 already. If I have 100 samples, it will reflect on chartjs?
Code:
var lineChartData = {
labels: parsedTime,
datasets: [
{
label: "Umidade",
data: parsedHumidity,
backgroundColor: [
"rgba(255, 99, 132, 0.2)",
"rgba(54, 162, 235, 0.2)",
"rgba(255, 206, 86, 0.2)",
"rgba(75, 192, 192, 0.2)",
"rgba(153, 102, 255, 0.2)",
"rgba(255, 159, 64, 0.2)"
],
borderColor: [
"rgba(255,99,132,1)",
"rgba(54, 162, 235, 1)",
"rgba(255, 206, 86, 1)",
"rgba(75, 192, 192, 1)",
"rgba(153, 102, 255, 1)",
"rgba(255, 159, 64, 1)"
],
borderWidth: 1
}
],
options: {
scales: {
yAxes: [
{
ticks: {
beginAtZero: true
}
}
]
}
}
};
Besides that, the API receives samples every 30 seconds. How can i show only the last 100 samples in real time?
Thank you guys
Upvotes: 0
Views: 982
Reputation: 1480
Chartjs provides the ability to add and remove data on the fly.
function addData(chart, label, data) {
chart.data.labels.push(label);
chart.data.datasets.forEach((dataset) => {
dataset.data.push(data);
});
chart.update();
}
function removeData(chart) {
chart.data.labels.pop();
chart.data.datasets.forEach((dataset) => {
dataset.data.pop();
});
chart.update();
}
Each time your api returns latest records, you will update your chart with the latest received data by using the above functions. Reference: https://www.chartjs.org/docs/latest/developers/updates.html
Upvotes: 1