[Chartjs]-Chart.js replace all data

9👍

You are creating a new chart, that’s why you end up with the old chart behind the new one.

One simple option that I’ve used:
Remove the old chart from the canvas that you are using for the chart:

$('#canvas').replaceWith('<canvas id="canvas"></canvas>');

And now create the chart with the new data in the same canvas

var ctxChart = document.getElementById("canvas").getContext("2d");
window.myChart = new Chart(ctxChart).Line(newdata, options);

Hope it helps!

1👍

For those of you wondering the same thing with Pie charts, doesn’t look like there’s a given public method that works but you can use an easy workaround by removing the data yourself:

var pieChart = new Chart(ctx).Doughnut(undefined, pieChartOptions);
pieChart.segments.splice(0, pieChart.segments.length);

Seems to work ok, wish they would just add a remove all method or make the clear actually work.

0👍

You are right, using the .update() function is the correct way to do this. I just answered the question on the other one you referenced but wanted to provide it here as well.

No need to delete the existing chart or do something like removing the canvas element to later append a new one. That works.. but isn’t necessary.

Working CodePen: https://codepen.io/vpolston/pen/KKRoEBY

Video walkthrough: https://www.youtube.com/watch?v=Ac5pzmHO3_A

Firstly if you want to know the why then I would recommend doing a console.log(myChart) of your chart object. You’ll see all kinds of properties that can be updated by simply assigning it a new value and then calling the myChart.update() on your chart.

Let’s say you have a chart that you called myChart when you instantiated it.. this part:

const myChart = new Chart('myChart', {}

The variable name is important. To update the dataset you silo down into what you saw when you console.log’d the chart. So your dataset would be

myChart.config.data.datasets[0].data

Just assign that a new value like this:

const newDatasArray = [1,52,23,23,48];
myChart.config.data.datasets[0].data = newDatasArray;

and then for the labels if you needed to change those:

const newLabelsArray = ["Jan", "Feb", "Mar", "Apr", "May"];
myChart.config.data.labels = newLabelsArray;

And then finally call the update function with myChart.update();

You’ll see the chart update to use the new dataset and/or labels.

Hopefully that gives a bit more insight into properly updating a chart. If you have a further question let me know and I’d be glad to try to help.

Thanks,
VP

Leave a comment