liveBook · Manning

D3.stack()

As explained in D3.js in Action, Third Edition

d3.stack() is the D3 API function that creates a stack layout for converting tabular series values into boundary coordinates.

d3.stack() creates a stack layout that transforms tabular series values into an annotated dataset of lower and upper boundaries. Configure the series with keys(), then call the generator with the input data. Each returned series carries its key, original data references, and one boundary pair per row: d[0] is the lower boundary and d[1] the upper boundary. section 5.2.1 section 5.4

const stackGenerator = d3.stack()  #1
  .keys(formatsInfo.map(f => f.id));  #2

const annotatedData = stackGenerator(data); #3

A minimal setup maps category IDs into keys, creates the stack generator, and produces the annotated dataset. section 5.2.1

Use the returned boundaries to build different visual forms:

  • Draw stacked bars by using each series’ lower and upper boundaries to position SVG rectangles. section 5.4
  • Draw a streamgraph with an area generator whose accessors read the lower and upper boundary values. section 5.4
  • Change stacking order with order() and baseline positioning with offset(); both choices affect the chart domain. section 5.4

Music-format sales

For yearly music-format data, keys derived from format IDs produce one series per format. The first series begins at zero, while later series use accumulated lower and upper boundaries; the year 1986 illustrates the resulting stacked columns. section 5.2.1

How D3.js in Action, Third Edition covers it

How deep it goes
Explains keys, invocation, multidimensional output, boundaries, order(), and offset(), but not generator internals.
Examples
Uses yearly music-format sales, format IDs, annotated series arrays, and a 1986 stacked-column illustration.
What it assumes
Assumes tabular input data and teaches how series keys and boundary pairs organize that data for drawing.
What you can do after
Build it from scratch by configuring keys and using returned boundaries to render stacked bars or streamgraphs.
How it connects
Connects stack layout with keys(), order(), offset(), SVG rectangles, area generators, stacked bar charts, and streamgraphs.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of D3.js in Action, Third Edition. The section links point to the parts of the book it draws on.