Stacked Area Chart

Learn how to draw a stacked area chart using d3.stack in D3.js.

Introduction

Let’s explore an important type of area chart, a stacked area chart. Stacked area charts are used to represent different values over time. It is used for showing trends over time among related attributes. Multiple related attributes are included in the stacked area chart, and they are all stacked upon each other. Before drawing a stacked area chart, let’s explore an API that is necessary to draw a stacked area chart.

Stacked generator

To create a stack in an area chart, we need to compute the y-value for each layer in the stacked area chart.

Thankfully, D3.js provides a stack generator, d3.stack(), that does this computation for us. Let’s see it in the following example where we have dummy data of a hospital in which we have three types of patients and we have to make three layers, one for each of them.

Console
d3.stack code

Explanation

As shown in the code above in

  • In line 18, we have defined a var stack using d3.stack().
  • Then we have initialized the keys() of stack, which defines the number of layers according to the data in stack.
  • In line 19, we have passed the data to the stack and we have stored the result in the s_data.
  • In line 20, we have printed the stacked data s_data on the console. We will see three objects, each representing a type of patient. For each object, we have values for nine months [0-8]. For the first month, we can see from the data the value for flu_patient ranges from 0 to 100, malaria_patients ranges from 100 to 200, and the value for dengue_patients ranges from 200 to 210, thus showing the behavior of layers in the stack.

Draw a stacked area chart

Now let’s draw a stacked area chart using d3.stack() and d3.area() in the following code.

Stacked area chart

Explanation

Only the highlighted code needs an explanation since the rest of the code is the same as in the previous lessons.

  • In line 37, we have defined the range from 0 to the max value of the last layer using the d3.max() function.
  • In line 45, we have initialized y0 to d[0], the starting y-value for each layer because now we have different y-values and not just zero, as was the case in the single-layer area chart.
  • Line 47-50: We have selected area and then we are binding s_data with the help of the data() function. For each data element, we are appending the g tag.
  • Line 51-53: We are drawing layers of the stacked area chart using path and area_generator. Then we filled each layer with color using the attr() method.