Data updates

An interactive chart may display data that is changing periodically. A web page might contain an algorithm that changes data automatically; it may download new data files with new data, or it may allow the user to enter or request changes in the source-data values. In any of these cases, as soon as the new data is available, the chart should be updated. Data updates can occur automatically inside callback functions or can be explicitly called using the update() command. To use it, you will need to save a variable handle to the chart object:

const chart = new Chart(…);
// make changes
chart.update();

When using callbacks, you can usually refer to the current instance of the chart, using the this keyword:

callback: function() {
// make changes
this.chart.update();
}

Changes usually involve properties in datasets and options of a chart instance. Let's see an example. In the following code, the square() function will square all the data values in a chart and change the x axis to a logarithmic scale. The squareRoot() function does the opposite. After updating the grid (with the undocumented scaleMerge() function), the chart is updated:

function square(chart) {
const datasets = chart.config.data.datasets;
for(let i = 0; i < datasets.length; i++) {
for(let j = 0; j < datasets[i].data.length; j++) {
let value = datasets[i].data[j];
datasets[i].data[j] = value * value;
}
}
chart.options.scales.yAxes =
Chart.helpers.scaleMerge(Chart.defaults.scale,
{yAxes: [{type: 'logarithmic'}]}).yAxes;
chart.update();
}

function squareRoot(chart) {
const datasets = chart.config.data.datasets;
for(let i = 0; i < datasets.length; i++) {
for(let j = 0; j < datasets[i].data.length; j++) {
let value = datasets[i].data[j];
datasets[i].data[j] = Math.sqrt(value);
}
}
chart.options.scales.yAxes =
Chart.helpers.scaleMerge(Chart.defaults.scale,
{yAxes: [{type: 'linear'}]}).yAxes;
chart.update();
}

The HTML button is registered as an event listener that calls one of the two functions, depending on the current y axis type, and updates the chart:

 let button = document.getElementById("toggle");
button.addEventListener('click', function() {
const type = myChart.options.scales.yAxes[0].type;
if(type == 'linear') {
square(myChart);
} else {
squareRoot(myChart);
}
});

Try it out. The full code is in Animation/animation-1-update.html, and the following screenshots show the chart in the two different states:

Updating a chart after changing values and scales. Code: Animation/animation-1-update.html.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset