Set an array to be displayed at Chart js

πŸ‘:0

The easiest way would be to just destroy the chart (using the chart variable) and construct a new chart using the new data.

For instance, if you already have constructed it using

...
var ctx = document.getElementById("chart").getContext("2d");
var myChart = new Chart(ctx).Bar(data);

You need to destroy it first using

myChart.destroy();

and then make the new chart

myChart = new Chart(ctx).Bar(newData);

where newData is the new data object.

You could also update the old data object (if you are not using it for anything else) instead of using a new object, like so

data.labels = [5, 6, 7, 8, 9]; 
data.datasets[0].data = [5, 6, 7, 8, 9]; 
myChart.destroy();
myChart = new Chart(ctx).Bar(data);

Fiddle – http://jsfiddle.net/5u3ahg7L/

(the chart updates with the new data after a 2 second delay, you don’t need the setTimeout wrapper – it’s just for demonstration)


You could also do this using the prototype methods .update() and .removeData() (http://www.chartjs.org/docs/#line-chart-prototype-methods for Line chart methods – each type has the similar methods) but since your changes require you to remove data from both ends of the graph, .destroy() would be an easier option.

Leave a comment