Accepted answer

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);


The only solution I can find so far for myself is to re-initialize the chart from scratch:

var myLineChart = new Chart(ctx).Line(data, options);

However this seems a bit hokey to me. Any better, more standard solution anybody?


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");
window.myLine = new Chart(ctx).Line(lineChartData, {


There is a way to do this without clearing the canvas or starting over, but you have to man handle the creation of the chart so that the data is in the same format for when you update.

Here is how I did it.

    var ctx = document.getElementById("myChart").getContext("2d");
    if (chartExists) {
        for (i=0;i<10;i++){
          console.log('chart doesnt exist');
          myNewChart = new Chart(ctx).Bar(dataNew);
          for (i=0;i<10;i++){
          for (i=0;i<10;i++){      

I basically scrap the data loaded in at creation, and then reform with the add data method. This means that I can then access all the points. Whenever I have tried to access the data structure that is created by the:


command, I can't access what I need. This means you can change all the data points, in the same way you created them, and also call update() without animating completely from scratch.


Chart JS 2.0

Just set = [];

For example:

function addData(chart, label, data) {; => {;

$ = [];

$.each(res.grouped, function(i,o) {
   addData($chart, o.age, o.count);


When creating the chart object you need to save the instance in a variable.

var currentChart = new Chart(ctx, ...);

And before loading new data, you need to destroy it:



Firstly, let a variable remember an instance of your chart.

             let yourChart = new Chart(ctxBar, {
                    type: 'bar',
                    data: {
                        labels: labels,
                        datasets: datasets

Secondly, the thing I mostly struggled with was getting the data structure in the right format before updating the chart. So after looking at the data key structure of chart js object:

  data: {
        labels: ['Jan', 'Feb'],
        datasets: [{
            label: 'Net sales',
            data: data
        }, {
            label: 'Cost of goods sold',
            data: data
        }, {
            label: 'Gross margin',
            data: data

Notice the data key value is an object consisting of two keys, labels and datasets. labels key' value is an array, while datasets key' value is also an array with an object as value.

Therefore, to remove labels and datasets from a chart instance I used: = []; = [{}];

To add labels and datasets to a chart instance I used: = ['label 1', 'label 2']; = [{
                label: 'column lables',
                data: [450, 50],
                backgroundColor: ["#dc3545", "#ffb759"]

Prepare server side
The labels and datasets values can be prepared server side as follows (in my case php):

$datajs = function ($data, $bg_colour) // function emulating chart js datasets key value structure
            return [
                'data' => $data,
                'backgroundColor' => $bg_colour
$datasets = [];
$labels = ['label 1', 'label 2'];
$datasets[] = $datajs([42,10], ["#dc3545", "#ffb759"]);
$datasets[] = $datajs([100,5], ["#dc3545", "#ffb759"]);

To just replace data from data key value from datasets (I did not test this) => { = [];
// if you have an array of arrays
let array = [[42,20],[58,68],[78,1]];
let length =;
for (let i = 0; i < array.length; i++) {
    const element = array[i];
    if (i < length) {[i].data = element;
    } else {[] = {data: element};


You need to clean old data. No need to re initialize:

for (i in myChartLine.datasets[0].points)


If anyone is looking for how to do this in React. For a linechart, assuming you have a wrapper component around the chart:

(This assumes you are using v2. You do not need to use react-chartjs. This is using the normal chart.js package from npm.)

propTypes: {
  data: React.PropTypes.shape({
    datasets: React.PropTypes.arrayOf(

    labels: React.PropTypes.array.isRequired
componentDidMount () {
  let chartCanvas = this.refs.chart;

  let myChart = new Chart(chartCanvas, {
    type: 'line',
    options: {

  this.setState({chart: myChart});
componentDidUpdate () {
    let chart = this.state.chart;
    let data =;

    data.datasets.forEach((dataset, i) =>[i].data =; = data.labels;
render () {
  return (
    <canvas ref={'chart'} height={'400'} width={'600'}></canvas>

The componentDidUpdate functionality allows you to update, add, or remove any data from the


None of the above answers helped my particular situation in a very clean way with minimal code. I needed to remove all datasets and then loop to add in several datasets dynamically. So this snipped is for those that make it all the way to the bottom of the page without finding their answer :)

Note: make sure to call chart.update() once you have loaded all of your new data into the dataset object. Hope this helps somebody

function removeData(chart) { = 0;

function addData(chart, data) {;


Please Learn how Chart.js (version 2 here) works and do it for whatever attribute you want:

1.Please suppose you have a bar chart like the below in your HTML:

<canvas id="your-chart-id" height="your-height" width="your-width"></canvas>

2.Please suppose you have a javascript code that fills your chart first time (for example when page is loaded):

var ctx = document.getElementById('your-chart-id').getContext('2d');
var chartInstance = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: your-lables-array,
        datasets: [{
            data: your-data-array,
            /*you can create random colors dynamically by ColorHash library []*/
            backgroundColor: (item) {
                return colorHash.hex(item);
    options: {
        maintainAspectRatio: false,
        scales: {
            yAxes: [ { ticks: {beginAtZero: true} } ]
        title: {display: true, fontSize: 16, text: 'chart title'},
        legend: {display: false}

Please suppose you want to update fully your dataset. It is very simple. Please look at the above code and see how is the path from your chart variable to data and then follow the below path:

  • select chartInstance var.
  • Then select data node inside the chartInstance.
  • Then select datasets node inside the data node.
    (note: As you can see, the datasets node is an array. so you have to specify which element of this array you want. here we have only one element in the datasets node. so we use datasets[0]
  • So select datasets[0]
  • Then select data node inside in the datasets[0].

This steps gives you[0].data and you can set new data and update the chart:[0].data = NEW-your-data-array
//finally update chart var:

Note: By following the above algorithm, you can simply achieve to each node you want.


I ran into the same issue, I have 6 pie charts on a page which can all be updated at the same time. I am using the following function to reset chart data.

// sets chart segment data for previously rendered charts
function _resetChartData(chart, new_segments) {
    // remove all the segments
    while (chart.segments.length) {

    // add the new data fresh
    new_segments.forEach (function (segment, index) {
        chart.addData(segment, index);

// when I want to reset my data I call
_resetChartData(some_chart, new_data_segments);


I tried neaumusic solution, but later found out that the only problem with destroy is the scope.

var chart;

function renderGraph() {
    // Destroy old graph
    if (chart) {

    // Render chart
    chart = new Chart(

Moving my chart variable outside the function scope, got it working for me.


Not is necesary destroy the chart. Try with this

function removeData(chart) {

        let total =;

        while (total >= 0) {



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){
    // Get the context of the canvas element we want to select
    var ctx = objChart.getContext("2d");
    myPieChart = new Chart(ctx).Pie(data, {animateScale: true});


My solution to this is pretty simple. (VERSION 1.X)

        var dataset = [];
        var arr1 = {
            label: " (myvalues1)",
            fillColor: "rgba(0, 138, 212,0.5)",
            strokeColor: "rgba(220,220,220,0.8)",
            highlightFill: "rgba(0, 138, 212,0.75)",
            highlightStroke: "rgba(220,220,220,1)",
            data: valuesArr1
        var arr2 = {
            label: " (myvalues2)",
            fillColor: "rgba(255, 174, 087,0.5)",
            strokeColor: "rgba(220,220,220,0.8)",
            highlightFill: "rgba(255, 174, 087,0.75)",
            highlightStroke: "rgba(220,220,220,1)",
            data: valuesArr2
        /*Example conditions*/
        if(condition 1)
        if(condition 2){

        return dataset;

var data = {
    labels: mylabelone,
    datasets: getDataSet()
if(myBarChart != null) // i initialize myBarChart var with null
    myBarChart.destroy(); // if not null call destroy
    myBarChart = new Chart(ctxmini).Bar(data, options);//render it again ...

No flickering or problems. getDataSet is a function to control what dataset I need to present


ChartJS 2.6 supports data reference replacement (see Note in update(config) documentation). So when you have your Chart, you could basically just do this: = ['1am', '2am', '3am', '4am'];[0].data = [0, 12, 35, 36];

It doesn't do the animation you'd get from adding points, but existing points on the graph will be animated.


It is an old thread, but in the current version (as of 1-feb-2017), it easy to replace datasets plotted on chart.js:

suppose your new x-axis values are in array x and y-axis values are in array y, you can use below code to update the chart.

var x = [1,2,3];
var y = [1,1,1];[0].data = y; = x;



With Chart.js V2.0 you can to do the following: = some_new_data;


You need to destroy:


Then re-initialize the chart:

var ctx = document.getElementById("myChartLine").getContext("2d");
myLineChart = new Chart(ctx).Line(data, options);

Related Query

More Query from same tag