The API for chart.js allows one to edit points of the datasets loaded into it, for example:
.update( )
Calling update() on
Not is necesary destroy the chart. Try with this
function removeData(chart) {
let total = chart.data.labels.length;
while (total >= 0) {
chart.data.labels.pop();
chart.data.datasets[0].data.pop();
total--;
}
chart.update();
}
With Chart.js V2.0 you can to do the following:
websiteChart.config.data = some_new_data;
websiteChart.update();
According to docs, clear()
clears the canvas. Think of it as the Eraser tool in Paint. It has nothing to do with the data currently loaded in the chart instance.
Destroying the instance and creating a new one is wasteful. Instead, use API methods removeData()
and addData()
. These will add/remove a single segment to/from the chart instance. So if you want to load completely new data, just loop a chart data array, and call removeData(index)
(array indexes should correspond to current segment indexes). Then, use addData(index)
to fill it with the new data. I suggest wrapping the two methods for looping the data, as they expect a single segment index. I use resetChart
and updateChart
. Before continuing, make sure you check Chart.js
latest version and documentation. They may have added new methods for replacing the data completely.
I answered this here see How to clear a chart from a canvas so that hover events cannot be triggered?
But here is the solution:
var myPieChart=null;
function drawChart(objChart,data){
if(myPieChart!=null){
myPieChart.destroy();
}
// Get the context of the canvas element we want to select
var ctx = objChart.getContext("2d");
myPieChart = new Chart(ctx).Pie(data, {animateScale: true});
}
Chart JS 2.0
Just set chart.data.labels = [];
For example:
function addData(chart, label, data) {
chart.data.labels.push(label);
chart.data.datasets.forEach((dataset) => {
dataset.data.push(data);
});
chart.update();
}
$chart.data.labels = [];
$.each(res.grouped, function(i,o) {
addData($chart, o.age, o.count);
});
$chart.update();
I had loads of trouble with this too. I have data and labels in separate arrays then I reinitialise the chart data. I added the line.destroy(); as suggested above which has done the trick
var ctx = document.getElementById("canvas").getContext("2d");
if(window.myLine){
window.myLine.destroy();
}
window.myLine = new Chart(ctx).Line(lineChartData, {
etc
etc