chartjs / Chart.js

Simple HTML5 Charts using the <canvas> tag
https://www.chartjs.org/
MIT License
63.9k stars 11.88k forks source link

Issue with Updating Charts -> Adding or Removing Data code example #11770

Closed philhd closed 1 month ago

philhd commented 1 month ago

Documentation Is:

Please Explain in Detail...

I tried directly using the functions in the example, but it was causing issues with the labels. Upon closer inspection of the code, it seems like it has some bugs (not all labels were removed).

Your Proposal for Changes

Here is what ended up working for me.

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

private removeData(chart: Chart) {
    chart.data.labels.length = 0;
    chart.data.datasets.length = 0;
    chart.update();
}

Example

No response

LeeLenaleee commented 1 month ago

The functions in https://www.chartjs.org/docs/4.4.0/samples/bar/horizontal.html seems to work fine. Can you give an example where it does not work, what happens and what did you expect?

philhd commented 1 month ago

Sorry, I should have been more specific. It's the code on this docs page: https://www.chartjs.org/docs/4.4.0/developers/updates.html#adding-or-removing-data

Specifically these two functions:

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

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

With a chart that has more than one element in chart.data.labels, removeData only removes one, so the chart ends up with leftover stale data.

LeeLenaleee commented 1 month ago

The current functions work as expected. They are not meant to replace or remove all the data.

They are meant to add a data entry to each dataset or remove a data entry from each dataset and that is exactly what the example is showing

philhd commented 1 month ago

Ah ok thanks for clarifying. I misunderstood the intent of the functions. I'll close this.