Loading data

Many times, your data will be available online and you may want to load it dynamically. It's also a good idea to keep your data and code in separate files. If you have data in a CSV file, you can load it into your JavaScript code and use it to generate the chart.

JavaScript loads data asynchronously using Ajax. You can use standard Ajax, JQuery, or the ES6 fetch function, which functions like a JavaScript promise. After you load the CSV file, you need to parse it. If you only need one set of category labels and values, you can handle it without a parser.

In this example, we will use a CSV file that contains the amount of plastic waste disposed of in the oceans by the 20 greatest pollutants. You can find the following code in the GitHub repository for this chapter in Data/waste.csv:

 Country,Tonnes
China,8819717
Indonesia,3216856
Philippines,1883659
...
United States,275424

The following code loads and parses the file, splitting the data into rows, and then splitting each row by a comma to assemble a labels array and a values array (we could also have used a CSV parser). This process transforms the data into arrays in a format that can be used by Chart.js, as follows:

fetch('../Data/waste.csv')
.then(response => response.text())
.then((data) => {
const labels = [],
values = [];
const rows = data.split(" ");

rows.forEach(r => {
const item = r.split(",");
labels.push(item[0]);
values.push(+item[1]);
});

labels.shift(); // remove the header
values.shift(); // remove the header

console.log(labels); // print to check if the arrays
console.log(values); // were generated correctly

draw(labels, values);

});

The draw() function contains the code to set up a canvas, and create and display the bar chart, as follows:

function draw(labels, values) {
const canvas = document.getElementById("bar-chart");
const ctx = canvas.getContext("2d");

new Chart(ctx, {
type: "bar",
data: {
labels: labels, // the labels
datasets: [
{
label: "Tonnes of plastic",
data: values, // the data values
borderWidth: 2,
backgroundColor: "hsla(20,100%,80%,0.8)",
borderColor: "hsla(0,100%,50%,1)"
}
]
},
options: {
maintainAspectRatio: false,
title: {
display: true,
text: 'Tonnes of plastic waste',
fontSize: 16
},
legend: {
display: false
}
}
});
}

You can view the full code in Pages/BarChart9.html. The result is shown as follows:

A bar chart created with data loaded from an external file (code: Pages/BarChart9.html)
..................Content has been hidden....................

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