Chartjs-How to pass a variable to the dataset for a graph in chart.js?

0๐Ÿ‘

โœ…

Iโ€™m not exactly sure what you are trying to achieve with your calculations if you update your answer I will be able to show you a working example, but to update the chart in real-time you will need to addData():

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

and possibly removeData():

function removeData(chart) {
    chart.data.labels.pop();
    chart.data.datasets.forEach((dataset) => {
        dataset.data.pop();
    });
    chart.update();
}

unless you replaceData():

function replaceData(chart, data) {
    chart.data.labels = Object.keys(data);
    chart.data.datasets.forEach((dataset) => {
        dataset.data = Object.values(data);
    });
    chart.update();
}

I have created an example fiddle showing implementation of addData

please refer to the docs

Leave a comment