Creating a simple pie chart

Let's create a simple pie chart to compare CO2 emissions among the world's greatest polluters for a single year. You can use the same data we used for the area chart, but you will need to choose one of the datasets, place the country names in a labels array, the data for one year in the data array, and generate colors for each slice. All this can be done in JavaScript (see Pie/pie-2-fetch.html), but for the sake of simplicity and to focus on the construction of a simple pie chart, we will include the data directly in the HTML file, as shown in the following code block:

 const dataset = [1.21, 1.71, 2.24, 3.24, 5.25, 10.29, 10.3]; // 2014 data
const labels = ["Japan", "Russian Federation", "India", "European Union",
"United States", "China", "Others"];
const colors = [];

dataset.forEach((entry, index) => { // generate some colors
colors.push('hsla('+((index+5)*50)+',75%,75%,1)');
});

The datasets array contains a single dataset, as follows:

const dataObj = {
labels: labels,
datasets: [{
data: dataset,
backgroundColor: colors,
borderWidth: 3
}]
}

The chart type should be pie, as follows:

const chartObj = {
type: "pie",
data: dataObj,
options:{
title: {
text: "CO2 emissions (billions of tonnes)",
display: true,
fontSize: 24
},
legend: {
labels: {
boxWidth: 20,
},
position: 'right'
}

}
};
new Chart("my-pie-chart", chartObj);

The results are shown as follows. You can also see the full code in Pie/pie-1.html. Note that slices don't have any labels. You can only see the value of each slice if you hover the mouse over it. It will be shown in a tooltip:

A simple pie chart showing CO2 emissions by the greatest polluters in billions of tonnes (code: Pie/pie-1.html)
..................Content has been hidden....................

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