Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 44 ยท Shapes and Paths

Area, Stacked Bar and Stacked Area Charts in D3

Build area charts with d3.area, then stack series with d3.stack into stacked bars, stacked areas and streamgraphs using stack order and offset options.

An area chart is a line chart with the region under (or between) lines filled. It emphasizes volume and total. When several series are drawn on top of each other, you get a stacked chart that shows both the parts and the whole. D3 has two helpers: d3.area() makes the shape, and d3.stack() computes the layered positions.

d3.area: a band between two lines

An area is bounded by a top line and a bottom line. For each point the generator needs x, a bottom y0 and a top y1. For the common "fill down to the axis" case, give y0 as a constant baseline.

JavaScript
const area = d3.area()
  .x(d => x(d.date))
  .y0(y(0))              // baseline (constant or function)
  .y1(d => y(d.value));  // top edge

path.datum(data).attr("d", area);

It supports the same .curve() and .defined() as d3.line, so smoothing and gaps work the same way. Often you draw an area with a light fill and a line on top for a crisp edge: use the line generator on the same data.

An area chart with a line on top

For a band such as a confidence interval or a min/max range, give both edges as data: .y0(d => y(d.low)).y1(d => y(d.high)).

d3.stack: computing layers

Stacking turns "wide" data (one row per x, one column per series) into layers. You tell the stack generator which keys (columns) to stack, and it returns one array per key. Each element is a pair [y0, y1] (bottom and top of that segment) and carries the original row in .data.

JavaScript
const rows = [
  { month: "Jan", apples: 10, pears: 5,  plums: 3 },
  { month: "Feb", apples: 12, pears: 7,  plums: 4 }
];

const stack = d3.stack().keys(["apples", "pears", "plums"]);
const layers = stack(rows);
// layers[0] = apples layer:  [[0, 10], [0, 12]]
// layers[1] = pears layer:   [[10, 15], [12, 19]]
// layers[2] = plums layer:   [[15, 18], [19, 23]]
// each layer also has .key, and each point has .data (the source row)

Each layer is a stack of positions: apples at the bottom, pears above them, plums on top. The generator also takes .value() (how to read a number from a row; the default is d[key]), .order() and .offset().

What d3.stack returns

Stacked bars

Draw each layer as a group colored by key, with one rectangle per row. The rectangle spans from y(d[1]) (top) to y(d[0]) (bottom).

A stacked bar chart

The first selectAll("rect").data(d => d) is a nested join: for each layer, the layer array itself is the data for its rectangles. The height uses y(p[0]) - y(p[1]) because the bottom pixel is larger than the top pixel.

Stacked areas and streamgraphs

Replace rectangles with one area per layer. The area generator takes the layer points as data: x from the source row, y0 from p[0], y1 from p[1].

JavaScript
const area = d3.area()
  .x(p => x(p.data.date))
  .y0(p => y(p[0]))
  .y1(p => y(p[1]));

g.selectAll("path.layer").data(layers).join("path")
  .attr("fill", d => color(d.key))
  .attr("d", area);

Two options change the look:

  • stack.order(...) sets layer order: d3.stackOrderNone (the key order), stackOrderAscending/Descending (by total size), stackOrderInsideOut (largest in the middle, used for streamgraphs), stackOrderReverse.
  • stack.offset(...) sets the baseline: d3.stackOffsetNone (zero baseline, default), stackOffsetExpand (normalize to 100 percent), stackOffsetSilhouette (center around the middle), stackOffsetWiggle (minimize movement, streamgraphs), and stackOffsetDiverging (positives above zero and negatives below).
Stacked area with offset options

The printed ranges show what each offset does to the baseline: zero-based, normalized 0 to 1, and a wiggle baseline that starts at 0 on the left and then drifts to keep the layers from jumping around.

Stacked charts make every layer except the bottom hard to compare, because they do not share a baseline. Use them to show parts-of-a-whole and the total. If the question is "which series is bigger over time", prefer separate lines or small multiples.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What do y0 and y1 mean in d3.area()?

    The area is the region between y0 (baseline) and y1 (top line).
  2. 2. What does each point in a d3.stack layer contain?

    Points are [bottom, top] pairs with the original row under .data. The layer also has a .key.
  3. 3. How can you create a 100 percent stacked chart?

    stackOffsetExpand normalizes every stack to the range 0 to 1.
  4. 4. In a stacked bar rectangle, what is the height?

    Pixel y grows downward, so the bottom y(p[0]) is greater than the top y(p[1]); their difference is the height.

Summary

  • d3.area() fills between y0 and y1; combine it with a line on top for a crisp edge.
  • d3.stack().keys([...]) turns wide rows into layers of [y0, y1] points carrying .data.
  • Draw stacks as nested joins of rects or as one area per layer; tune order and offset for 100 percent or stream looks.
  • Stacked charts show totals and parts, not easy comparison of inner series.

Next: Pie and Donut Charts with d3.arc