Stacked Area Chart
Learn how to draw a stacked area chart using d3.stack in D3.js.
We'll cover the following
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.
Explanation
As shown in the code above in
- In line 18, we have defined a
var stack
usingd3.stack()
. - Then we have initialized the
keys()
ofstack
, which defines the number of layers according to the data instack
. - In line 19, we have passed the
data
to thestack
and we have stored the result in thes_data
. - In line 20, we have printed the stacked data
s_data
on the console. We will see threeobjects
, 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 forflu_patient
ranges from0
to100
,malaria_patients
ranges from100
to200
, and the value fordengue_patients
ranges from200
to210
, 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.
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 thed3.max()
function. - In line 45, we have initialized
y0
tod[0]
, the startingy-value
for each layer because now we have differenty-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 bindings_data
with the help of thedata()
function. For each data element, we are appending theg
tag. - Line 51-53: We are drawing layers of the stacked area chart using
path
andarea_generator
. Then we filled each layer with color using theattr()
method.