Stacked area charts in d3

Published
2019-05-13
Tagged

You can do stacked area charts in d3 using d3.stack. It’s pretty cool:

1
d3.csv("wide-data.csv").then(function(data) {
2
  let svg = d3.select(".ex1");
3
4
  // Formatting and scaling code, and then...
5
6
  let stacker = d3.stack()
7
    .keys(["Apples", "Bananas", "Canteloupes"]);
8
9
  let stackedData = stacker(data);
10
11
  let areaGen = d3.area()
12
    .x((d,i) => x(i))
13
    .y0(d => y(d[0]))
14
    .y1(d => y(d[1]));
15
16
  let fillColours = ["red", "blue", "green"];
17
18
  svg.selectAll("path")
19
    .data(stackedData)
20
    .enter()
21
      .append("path")
22
      .attr("d", series => areaGen(series))
23
      .style("fill", (d,i) => fillColours[i]);
24
  });

It’s not the easiest thing to use, especially if you’re a worshipper at the [altar of tidy data][tidydata]. So how do you turn a long array of data, with categories encoded in their own column, into a stacked area chart?

The good news is that it’s not hard. It’s just a bit long-winded.

First, find your areas…

A stacked area chart is basically a set of polygons, which we can handily plot using d3’s area generator. But first, we need to determine the “stacking order” of our chart: which series should go at the bottom, which should go on top, etc. This is a bit subjective, depending on what you’re showing, but an adequate rule of thumb (at least for right now) is that the biggest areas should be on the bottom.

1
// This data has columns: TimePeriod, Fruit, Value
2
d3.csv(
3
  "long-data.csv",
4
  function(row){
5
    //Convert to numeric values
6
    row.Value = +row.Value;
7
    row.TimePeriod = +row.TimePeriod;
8
    return row;
9
  }).then(function(data) {
10
11
    // Sum up totals for each fruit
12
    let fruitSums = d3.nest()
13
      .key(d => d.Fruit)
14
      .rollup(d => d.map(e => e.Value).reduce((a,b) => a + b))
15
      .entries(data);
16
17
    // > [
18
    // >   0: {key: "Canteloupes", value: 182.99031444}
19
    // >   1: {key: "Apples", value: 314.94202225000004}
20
    // >   2: {key: "Bananas", value: 327.70480420999996}
21
    // > ]
22
23
    // We do b - a because we wish to sort in descending order.
24
    let fruitOrder =
25
      fruitSums
26
      .sort((a,b) => b.value - a.value)
27
      .map(a => a.key);
28
29
    // > ["Bananas", "Apples", "Canteloupes"]
30
});

Now we know the order we want: Bananas on the bottom, Canteloupes on the top. But we’re still faced with the issue of how we stack the areas on top of one another.

This bit is kind of clever, even while being pretty straightforward. For each time period, we calculate two values for every series:

  • The floor, which is the sum of all values “below” this value on the stack.
  • The ceiling, which is the sum of the floor and this series’ value at this point.

It sounds easy, but it’s a bit tricky. We’re going to make some clever shortcuts, but we’re still going to have to group this data by time period, and ungroup it again:

1
// Inside the csv call above...
2
let stackData = d3.nest()
3
  .key(d => d.TimePeriod)
4
  .rollup(function(d) {
5
    let sortedData = d.sort((a,b) => fruitOrder.indexOf(a.Fruit) - fruitOrder.indexOf(b.Fruit));
6
    let sortedValues = sortedData.map(d => d.Value);
7
8
    return sortedData.map(function(row, i) {
9
      let floor = i == 0 ? 0 : sortedValues.slice(0, i).reduce((a,b) => a + b);
10
      let ceiling = sortedValues.slice(0, i + 1).reduce((a,b) => a + b);
11
12
      return {
13
        "Fruit": row.Fruit,
14
        "TimePeriod": row.TimePeriod,
15
        "Floor": floor,
16
        "Ceiling": ceiling
17
      };
18
    });
19
  })
20
  .entries(data);
21
22
// Ungroup data!
23
stackData = stackData.map(kv => kv.values).reduce((x,y) => x.concat(y));

What’s happening here? First, we nest the data by time period (because we’re stacking up data for each time period). We take data for each time period, and sort is according to the order we specified above. We then make an (ordered) list of values to graph, and, going through the data, create the floor and ceiling variables.

Once we’ve done all that, we have a dictionary that looks like the following:

1
[
2
  {
3
    key: "1",
4
    value: [
5
      0: {Fruit: "Bananas", TimePeriod: 1, Floor: 0, Ceiling: 17.44394906}
6
      1: {Fruit: "Apples", TimePeriod: 1, Floor: 17.44394906, Ceiling: 28.056471180000003}
7
      2: {Fruit: "Canteloupes", TimePeriod: 1, Floor: 28.056471180000003, Ceiling: 36.370769893}
8
    ]
9
  },
10
  {
11
    key: "2",
12
    ...
13
  }
14
]

In the last line of the code above, we extract the value object and concatenate each array together, to give our final un-nested array of data.

Then stack them!

This part is pretty easy: we use the above Floor and Ceiling values to produce an area chart.

1
let svg = d3.select(".ex2");
2
3
svg.attr("viewBox", "0 0 40 20");
4
5
let x = d3.scaleLinear()
6
  .domain(d3.extent(stackData, d => d.TimePeriod))
7
  .range([0, 40]);
8
9
let y = d3.scaleLinear()
10
  .domain([d3.min(stackData, d => d.Floor), d3.max(stackData, d => d.Ceiling)])
11
  .range([20, 0]);
12
13
let areaGen = d3.area()
14
  .x (d => x(d.TimePeriod))
15
  .y0(d => y(d.Floor))
16
  .y1(d => y(d.Ceiling));
17
18
let fillColours = ["red", "blue", "green"];
19
20
// Add data, nested by fruit
21
let nestedData = d3.nest()
22
  .key(d => d.Fruit)
23
  .entries(stackData);
24
25
svg.selectAll("path")
26
  .data(nestedData, d => d.key)
27
  .enter()
28
    .append("path")
29
    .attr("d", series => areaGen(series.values))
30
    .style("fill", (d,i) => fillColours[i]);

Let’s see it in action!

The graph below is generated using all the code we wrote above. Want to see what it looks like? Check out the source.

What next?

The example I’ve shown here is pretty specific - if you change the format of the data, you’re going to have to change the code. We’re nowhere near the d3.longStack() example posted above. What we have, though, is a proof-of-concept: we’ve gone from an idea to an actual implementation.

The process of making a general function for the long-data stacked area chart is left as an exercise to the reader.