score:111

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

score:0

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?

score:0

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

score:0

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++){
            mynewchart.scale.xlabels[i]=dblabels[i]; 
            mynewchart.datasets[0].bars[i].value=dbonair[i];
        }
        mynewchart.update();
      }else{
          console.log('chart doesnt exist');
          mynewchart = new chart(ctx).bar(datanew);
          mynewchart.removedata();
          for (i=0;i<10;i++){
              mynewchart.adddata([10],dblabels[i]);
          }
          for (i=0;i<10;i++){      
              mynewchart.datasets[0].bars[i].value=dbonair[i];
          }
          mynewchart.update();
          chartexists=true;
        }

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:

chart(ctx).bar(datanew);

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.

score:0

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

score:0

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:

currentchart.destroy();

score:0

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:

yourchart.data.labels = [];
yourchart.data.datasets = [{}];
yourchart.update();

to add labels and datasets to a chart instance i used:

yourchart.data.labels = ['label 1', 'label 2'];
yourchart.data.datasets = [{
                label: 'column lables',
                data: [450, 50],
                backgroundcolor: ["#dc3545", "#ffb759"]
            }];
yourchart.update();

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)

yourchart.data.datasets.foreach((dataset) => {
    dataset.data = [];
});
yourchart.update();
// if you have an array of arrays
let array = [[42,20],[58,68],[78,1]];
let length = yourchart.data.datasets.length;
for (let i = 0; i < array.length; i++) {
    const element = array[i];
    if (i < length) {
        yourchart.data.datasets[i].data = element;
    } else {
        yourchart.data.datasets[] = {data: element};
    }
}
yourchart.update();

score:2

you need to clean old data. no need to re initialize:

for (i in mychartline.datasets[0].points)
    mychartline.removedata();

score:2

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(
      react.proptypes.shape({

      })
    ),
    labels: react.proptypes.array.isrequired
  }).isrequired
},
componentdidmount () {
  let chartcanvas = this.refs.chart;

  let mychart = new chart(chartcanvas, {
    type: 'line',
    data: this.props.data,
    options: {
      ...
    }
  });

  this.setstate({chart: mychart});
},
componentdidupdate () {
    let chart = this.state.chart;
    let data = this.props.data;

    data.datasets.foreach((dataset, i) => chart.data.datasets[i].data = dataset.data);

    chart.data.labels = data.labels;
    chart.update();
},
render () {
  return (
    <canvas ref={'chart'} height={'400'} width={'600'}></canvas>
  );
}

the componentdidupdate functionality allows you to update, add, or remove any data from the this.props.data.

score:3

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) {
   chart.data.datasets.length = 0;
}

function adddata(chart, data) {
  chart.data.datasets.push(data);
}

score:3

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 [https://github.com/zenozeng/color-hash]*/
            backgroundcolor: your-lables-array.map(function (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 chartinstance.data.datasets[0].data and you can set new data and update the chart:

chartinstance.data.datasets[0].data = new-your-data-array
//finally update chart var:
chartinstance.update();


note: by following the above algorithm, you can simply achieve to each node you want.

score:4

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) {
        chart.removedata();
    };

    // 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);
some_chart.update();

score:4

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) {
        chart.destroy();
    }

    // render chart
    chart = new chart(
        document.getelementbyid(idchartmainwrappercanvas),
        chartoptions
    );
}

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

score:4

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

score:6

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.

score:8

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

score:12

my solution to this is pretty simple. (version 1.x)

getdataset:function(valuesarr1,valuesarr2){
        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)
          dataset.push(arr1);
        }
        if(condition 2){
          dataset.push(arr1);
          dataset.push(arr2);
        }

        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

score:18

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:

mychart.data.labels = ['1am', '2am', '3am', '4am'];
mychart.data.datasets[0].data = [0, 12, 35, 36];
mychart.update();

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

score:25

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

chart.data.datasets[0].data = y;
chart.data.labels = x;

chart.update();

score:47

with chart.js v2.0 you can to do the following:

websitechart.config.data = some_new_data;
websitechart.update();

score:71

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

Related Query

More Query from same tag