Completely Refresh Chart.js Data

The chart has been updated with an external brush, which can be activated by clicking on a link. My goal is to develop a chaining function that can generate a bar chart.

Question:

By utilizing the API of

chart.js

, it is feasible to modify the points of the datasets that are loaded into the system.


.update( )

By invoking update() method on your Chart object, you can redraw the chart with new values. This enables you to modify multiple data points and display them in a single animation cycle.


.addData( valuesArray, label )

To add data to your Chart instance, provide an array of values for each dataset and assign a label to those points using the addData(valuesArray, label) method.


.removeData( )

If you call removeData() on your Chart instance, it will delete the initial value of each dataset present on the chart.

While all the options are impressive, I’m struggling to understand the process of replacing the old dataset with a new one. Unfortunately, the documentation doesn’t provide any guidance on this matter.


Solution 1:

I had huge problems with this

Initially, I attempted to use

.clear()

. Subsequently, I experimented with

.destroy()

. In addition, I attempted to reset my chart reference to null.

The solution that worked for me was to remove the

<canvas>

component and subsequently add a new

<canvas>

to the main container.


There’s a million ways to do this:

var resetCanvas = function () {
  $('#results-graph').remove(); // this is my  element
  $('#graph-container').append('');
  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);
};


Solution 2:

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


Solution 3:


Using version 2.0 of
chart.js
, you are able to accomplish the subsequent tasks:

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


Solution 4:

Although the thread may be old, replacing datasets on chart.js is a simple task in the current version as of 1-Feb-2017.

If your x-
axis values
are stored in the array ‘x’, and the corresponding y-axis values are stored in the array ‘y’, then the chart can be easily updated using the following code.

var x = [1,2,3];
var y = [1,1,1];
chart.data.datasets[0].data = y;
chart.data.labels = x;
chart.update();

Frequently Asked Questions