chart.js load totally new data
The API for chart.js
allows one to edit points of the datasets loaded into it, for example:
.update( )
Calling update() on your Chart instance will re-render the chart with any updated values, allowing you to edit the value of multiple existing points, then render those in one animated render loop.
.addData( valuesArray, label )
Calling addData(valuesArray, label) on your Chart instance passing an array of values for each dataset, along with a label for those points.
.removeData( )
Calling removeData() on your Chart instance will remove the first value for all datasets on the chart.
All of these are great, but I cannot figure out how to load an entirely new dataset in, wiping out the old. The documentation does not seem to cover this.
Solution 1:
I had huge problems with this
First I tried .clear()
then I tried .destroy()
and I tried setting my chart reference to null
What finally fixed the issue for me: deleting the <canvas>
element and then reappending a new <canvas>
to the parent container
There's a million ways to do this:
var resetCanvas = function () {
$('#results-graph').remove(); // this is my <canvas> element
$('#graph-container').append('<canvas id="results-graph"><canvas>');
canvas = document.querySelector('#results-graph'); // why use jQuery?
ctx = canvas.getContext('2d');
ctx.canvas.width = $('#graph').width(); // resize to parent width
ctx.canvas.height = $('#graph').height(); // resize to parent height
var x = canvas.width/2;
var y = canvas.height/2;
ctx.font = '10pt Verdana';
ctx.textAlign = 'center';
ctx.fillText('This text is centered on the canvas', x, y);
};
Solution 2:
You need to destroy:
myLineChart.destroy();
Then re-initialize the chart:
var ctx = document.getElementById("myChartLine").getContext("2d");
myLineChart = new Chart(ctx).Line(data, options);
Solution 3:
With Chart.js V2.0 you can to do the following:
websiteChart.config.data = some_new_data;
websiteChart.update();