Chart.js uploads brand new data

The chart.js API allows chart.js to edit the points of the data sets loaded into it, for example:

.update( )

The update call () in the chart instance redraws the chart using any updated values, allowing you to edit the value of several existing points, and then visualize them in one animated rendering cycle.

.addData( valuesArray, label )

A call to addData (valuesArray, label) on the Chart instance, passing an array of values ​​for each data set along with a label for these points.

.removeData( )

Calling removeData () on the chart instance will remove the first value for all datasets in the chart.

All this is great, but I can’t figure out how to load a completely new dataset, destroying the old one. The documentation does not seem to cover this.

+75
javascript
Jul 16 '14 at 16:15
source share
17 answers

I had huge problems with this

First I tried .clear() , then I tried .destroy() , and I tried to set the reference to the diagram to zero

Which finally fixed the problem for me: removing the <canvas> and then reusing the new <canvas> in the parent container




There are 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); }; 
+88
Jul 31 '14 at 16:14
source share

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); 
+55
Nov 17 '14 at 22:34
source share

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

 websiteChart.config.data = some_new_data; websiteChart.update(); 
+34
Apr 29 '16 at 18:51
source share

This is an old thread, but in the current version (starting from February 1, 2017) it is easy to replace datasets built on chart.js:

Suppose your new x-axis values ​​are in the x array and the y-axis values ​​are in the y array, you can use the code below 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(); 
+16
Feb 01 '17 at 13:44 on
source share

My solution 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 which dataset I need to present

+11
Jan 18 '16 at 10:36
source share

ChartJS 2.6 supports replacing data links (see Note in the documentation for updating (configuration)). Therefore, when you have a chart, you can simply do this:

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

It does not perform the animation that you get from adding points, but existing points on the chart will be animated.

+10
Oct 05 '17 at 13:58 on
source share

I answered this here by looking at 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
Jun 05 '15 at 23:19
source share

According to the docs, clear() clears the canvas. Think of it as an Eraser tool in Paint. It has nothing to do with the data that is currently loaded in the chart instance.

Destroying an instance and creating a new one is wasteful. Instead, use the removeData() and addData() API methods. They will add / remove one segment to / from the chart instance. Therefore, if you want to load completely new data, simply loop the chart data array and call removeData(index) (the array indices must correspond to the indices of the current segment). Then use addData(index) to populate it with new data. I propose combining the two methods for data cyclization, since they expect the index of one segment. I am using resetChart and updateChart . Before continuing, make sure you check the latest version and documentation of Chart.js . They may have added new methods to completely replace the data .

+6
Nov 18 '15 at 18:56
source share

I ran into the same problem, I have 6 pie charts per page that can be updated at the same time. I use the following function for 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(); 
+4
Sep 30 '14 at 23:28
source share

I tried the neaumusic solution, but later found out that the destruction problem is Volume .

 var chart; function renderGraph() { // Destroy old graph if (chart) { chart.destroy(); } // Render chart chart = new Chart( document.getElementById(idChartMainWrapperCanvas), chartOptions ); } 

Moving my chart variable out of scope made it work for me.

+3
May 7 '17 at 12:50
source share

You need to clear the old data. There is no need to reinitialize:

 for (i in myChartLine.datasets[0].points) myChartLine.removeData(); 
+2
Jan 09 '15 at 4:31 on
source share

None of the above answers helped my specific situation in a very clean form with minimal code. I needed to delete all data sets and then a loop to add dynamically to multiple data sets. Thus, it is cut off for those who do it all the way to the bottom of the page without finding an answer :)

Note. Be sure to call chart.update () after loading all the new data into the dataset object. Hope this helps someone.

 function removeData(chart) { chart.data.datasets.length = 0; } function addData(chart, data) { chart.data.datasets.push(data); } 
+2
Jul 31 '17 at 14:19
source share

If someone is looking for how to do this in React. For a line assuming you have a wrapper component around a chart:

(This assumes you are using v2. You do not need to use react-chartjs . This is a regular 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 this.props.data .

+1
May 4 '16 at 23:33
source share

The only solution that I can still find for myself is to reinitialize the chart from scratch:

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

However, this seems a little shocking to me. Any better, more standard solution - anyone?

0
Jul 16 '14 at 16:18
source share

I also had problems with this. I have data and labels in separate arrays, after which I reinitialize the chart data. I added the line .destroy (); as suggested above that did 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
Jan 10 '15 at 11:35
source share

There is a way to do this without clearing the canvas or starting with it, but you have to control the creation of the chart so that the data is in the same format 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 discard the data loaded at creation, and then reform the method of adding data. This means that I can access all points. Whenever I tried to access a data structure created with:

 Chart(ctx).Bar(dataNew); 

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

0
Apr 01 '16 at 19:55
source share

JS 2.0 Chart

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
Jul 16 '19 at 13:22
source share



All Articles