Updating charts

You can use JavaScript functions and libraries to change your data dynamically, but the changes will not be reflected immediately in your chart. After changing data, you have to call update() in order to redraw it. For this, you will need a variable reference to the chart object, as follows:

const ch = new Chart("ocean-volume-bar-chart", {...});

The following example toggles the data in the chart, replacing the values in the dataset with a different array, and changing labels, titles, and colors. The toggle() function is registered as a click event listener on the canvas. Whenever you click anywhere in the canvas it will run, change the values of several properties, and call update(),which forces the chart to transition to the new data and appearance, as follows:

const labels = ["Arctic", "North Atlantic", "South Atlantic", "Indian",
"North Pacific", "South Pacific", "Southern"];

const area = [15558,41900,40270,70560,84000,84750,21960]; // km2 * 10^3
const volume = [18750,146000,160000,264000,341000,329000,71800]; //km3 * 10^3
const canvas = document.getElementById("ocean-volume-bar-chart");
const ctx = canvas.getContext("2d");
const ch = new Chart(ctx, {
type: "bar",
data: {
labels: labels,
datasets: [
{
label: "Volume",
data: volume,
borderWidth: 2,
backgroundColor: "hsla(20,100%,80%,0.8)",
borderColor: "hsla(0,100%,50%,1)"
}
]
},
options: {
maintainAspectRatio: false,
title: {
display: true,
text: ['Volume of the oceans','in thousands of cubic km'],
fontFamily: "TrebuchetMS",
fontSize: 24
},
legend: {
display: false
}
}
});

canvas.addEventListener("click", toggle);

function toggle(event) {
if(ch.data.datasets[0].label == "Volume") {
ch.data.datasets[0].data = area;
ch.data.datasets[0].label = "Area";
ch.data.datasets[0].borderColor = "hsla(120,100%,50%,1)";
ch.data.datasets[0].backgroundColor = "hsla(140,100%,80%,0.8)";
ch.options.title.text = ['Surface area of the oceans',
'in thousands of square km'];
} else {
ch.data.datasets[0].data = volume;
ch.data.datasets[0].label = "Volume";
ch.data.datasets[0].backgroundColor = "hsla(20,100%,80%,0.8)";
ch.data.datasets[0].borderColor = "hsla(0,100%,50%,1)";
ch.options.title.text = ['Volume of the oceans',
'in thousands of cubic km'];
}
ch.update();
}

The following screenshot shows the same chart before and after being clicked. The full code is available at Pages/BarChart7.html:

Screenshots of same chart after and before a click. Code: Pages/BarChart7.html
..................Content has been hidden....................

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