Adding extra datasets

You can add more datasets to a bar chart, and configure it with a new legend label, colors, and data arrays. In the following example, we will load a larger .csv file, which contains the data for plastic waste disposal in 2010, and a forecast for 2025. It has one extra column, as follows:

 Country,2010,2025
China,8819717,17814777
Indonesia,3216856,7415202
Philippines,1883659,5088394
...
United States,275424,336819

This time, the code will generate two data arrays and a single labels array. The data and labels that belong to the same category have the same index, as follows:

fetch('../Data/waste2.csv')
.then(response => response.text())
.then((data) => {
const labels = [],
values2010 = [],
values2025 = [];

const rows = data.split(" ");

rows.forEach(r => {
const item = r.split(",");
labels.push(item[0]);
values2010.push(+item[1]/1000000); // divide by 1 million to make
values2025.push(+item[2]/1000000); // the chart easier to read
});

labels.shift();
values2010.shift();
values2025.shift();

draw(labels, [values2010, values2025]);

});

The new values will be included in a second dataset, in the datasets array, as follows.

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

new Chart(ctx, {
type: "horizontalBar",
data: {
labels: labels,
datasets: [
{
label: "2010",
data: values[0],
backgroundColor: "hsla(20,100%,50%,0.7)",
},{
label: "2025",
data: values[1],
backgroundColor: "hsla(260,100%,50%,0.7)",
}
]
},
options: {
maintainAspectRatio: false,
title: {
display: true,
text: 'Millions of tonnes of plastic waste',
fontSize: 16
}
}
});
}

The full code is in Pages/BarChart12.html. With two datasets, there are two bars for each category. There is also one legend item for each dataset. The result is shown in the following screenshot:

A bar chart with two datasets (code: Pages/BarChart12.html)

With two or more datasets, you may want to configure the width of the bars using the configuration option properties, barPercentage and categoryPercentage. The former controls the width of the individual bars for each category, and the latter determines the space taken by all of the bars in one category. These properties should be defined in options.scales.xAxes[] if you are using a bar chart, and options.scales.yAxes[] if it is a horizontalBar (see Pages/BarChart12.html), as follows:

options: {
maintainAspectRatio: false,
title: {
display: true,
text: 'Tonnes of plastic waste',
fontSize: 16
},
scales: {
yAxes: [{
barPercentage: .3,
categoryPercentage: .5
}]
}
}
..................Content has been hidden....................

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