Stacking bars

Bars are usually placed side-by-side for comparison. However, if the values are part of a whole, you can stack bars in different datasets to emphasize this relationship. We can stack the volumes of the world's oceans, since their sum reveals the total volume of ocean water in the world. The following data object places the volume of each ocean in a separate dataset, as follows:

const dataObj = {
labels: ["Volume"], // there is only one category
datasets: [
{
label: "Arctic", data: [18750],
backgroundColor: "hsla(0,100%,50%,0.5)"
},{
label: "North Atlantic", data: [146000],
backgroundColor: "hsla(60,100%,50%,0.5)"
},{
label: "South Atlantic", data: [160000],
backgroundColor: "hsla(120,100%,50%,0.5)"
},{
label: "Indian", data: [264000],
backgroundColor: "hsla(180,100%,50%,0.5)"
},{
label: "North Pacific", data: [341000],
backgroundColor: "hsla(240,100%,50%,0.5)"
},{
label: "South Pacific", data: [329000],
backgroundColor: "hsla(300,100%,50%,0.5)"
},{
label: "Southern", data: [71800],
backgroundColor: "hsla(340,100%,50%,0.5)"
},
]
};

To transform a bar chart into a stacked chart, you have to configure the settings for the x and y axes, enabling the stacked property as follows:

 const optionsObj = {
maintainAspectRatio: false,
title: {
display: true,
text: 'Volume of oceans (km3)',
fontSize: 16
},
legend: {
position: 'right'
},
scales: {
xAxes: [{
stacked: true
}],
yAxes: [{
stacked: true
}]
}
}
new Chart("ocean-volume-bar-chart",
{type: "bar", data: dataObj, options: optionsObj});

The expected result is shown in the following screenshot. The full code is in Pages/BarChart13.html:

A stacked bar chart can be used to display data as parts of a whole (code: Pages/BarChart13.html)
..................Content has been hidden....................

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