...

/

Drawing the Stacked Bars

Drawing the Stacked Bars

Drawing stacked data means we should draw our bars in groups to keep things organized.

We'll cover the following...

We are going to draw the stacked bars using our scales. Unlike other charts, we are going to take two steps for drawing the bars. First, we need to loop through the formatted data. The formatted data is an array of age groups. On each iteration, we will loop through the data inside the age group. For each iteration, we will draw a bar. In total, there should be 468 bars drawn on the image.

Creating groups

In the script, at the bottom of the draw() function, we will add the following code:

Press + to interact
// Draw Bars
const ageGroups = ctr.append("g")
.classed('age-groups', true)
.selectAll("g")
.data(stackData)
.join("g")

We are adding a group to keep things organized. The group is assigned to a variable called ageGroups. We are going to be drawing a lot of shapes for this example. It would be a good idea to group things together to make it easier for debugging.

To make it easier to identify, we are adding a class called age-groups. The class does not come with any styles. We are adding it to help us find the group in the image with the developer tools. After adding the class, we will make a selection for an empty group with the select all function.

We are joining the stackData array with the selection by calling the data() function. Since there are not elements for the data to be joined with, they will be placed inside the enter selection. We can draw some shapes based on the data in the enter selection by calling the join() function. Instead of drawing a shape, we are creating another group.

We are attempting to draw the bars, but however, the data for the bars are nested inside the array. To access the bars, we will need to join the ...