93
votes

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.

21

21 Answers

104
votes

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

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

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

websiteChart.config.data = some_new_data;
websiteChart.update();
23
votes

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

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.

12
votes

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

8
votes

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

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.

4
votes

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

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.

3
votes

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

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

for (i in myChartLine.datasets[0].points)
    myChartLine.removeData();
2
votes

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

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


<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:each node you want
1
votes

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.

0
votes

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?

0
votes

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
0
votes

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.

0
votes

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

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

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