Issue
I just learned to make a web And I want to know how to make chart js to display values in real time. Can you guys advise or tell me how to do it for me?
var data = [];
var temp = [];
async function getRandomUser() {
const response = await fetch('http://localhost:1111/chartpie');
const data = await response.json();
addData(data);
}
function addData(object) {
temp.push(object.temperature);
var z = 80;
var y = z - temp;
var ctx = document.getElementById("myPieChart");
myPieChart = new Chart(ctx, {
type: "doughnut",
data: {
labels: ["Temperature", "Null"],
datasets: [{
data: [temp, y],
backgroundColor: [
"orange",
"rgba(0, 172, 105, 1)"
],
}]
},
options: {
legend: {
display: false
},
}
});
}
getRandomUser()
The values I retrieved are the values retrieved from mongoDB, fetched in the form of an array. Thank You!
Solution
You can just update the chart in "real time" by adding to the charts data array.
see: https://www.chartjs.org/docs/latest/developers/updates.html
Adding and removing data is supported by changing the data array. To add data, just add data into the data array as seen in this example.
function addData(chart, label, data) {
chart.data.labels.push(label);
chart.data.datasets.forEach((dataset) => {
dataset.data.push(data);
});
chart.update();
}
For example...
const canvas = document.getElementById('myChart');
canvas.height = 75;
const labels = [
'dju32',
'ad6b2',
'0f23f',
'asd4c',
];
const data = {
labels: labels,
datasets: [{
label: 'Test',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: [0, 10, 5, 4],
}]
};
const config = {
type: 'line',
data: data,
options: {}
};
const myChart = new Chart(
canvas,
config
);
// function to update the chart
function addData(chart, label, data) {
chart.data.labels.push(label);
chart.data.datasets.forEach((dataset) => {
dataset.data.push(data);
});
chart.update();
}
// randomly add new data
setInterval(function() {
const newLabel = (Math.random() + 1).toString(36).substring(7);
const newData = Math.floor(Math.random() * 10);
addData(myChart, newLabel, newData);
}, 1000);
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<div>
<canvas id="myChart"></canvas>
</div>
Answered By - Fraser
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.