Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 7.2 — Stacked and Grouped Bars and Areas
Data Visualization · Example 1 of 2

What d3.stack lays out: [y0, y1] for every item

Each series is an array of [y0, y1] pairs. The JSON shows null where D3 holds NaN. Nothing in d3.stack throws: bad input gives bad numbers, and the error appears later, in the SVG.

d3.stack adds up several series so that each bar or area starts where the one below it ends. You choose the order and the offset (plain, 100%, or above and below zero), and you learn which questions a stack answers and which it hides.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 4 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Take the first example's months and print, for February, how many rides the pedal series covers (y1 - y0). Use d3.stack().keys(["ebike", "pedal"]).

02

Turn step 2 into a chart of the two largest districts and one "Other" series that adds the rest. Hint: build the wide table again with three keys.

Explain it without notes

01

What does d3.stack return for one month and one key?

02

When would you choose grouped bars over stacked bars?

03

What can a 100% stack show that a normal stack cannot, and what does it lose?

What d3.stack lays out: [y0, y1] for every item

Console

(nothing was printed)

Expected console output

ebike, pedal       [["ebike",[[0,3],[0,5]]],["pedal",[[3,5],[5,6]]]]
pedal, ebike       [["pedal",[[0,2],[0,1]]],["ebike",[[2,5],[1,6]]]]
expand (100%)      [["ebike",[[0,0.6],[0,0.8333333333333334]]],["pedal",[[0.6,1],[0.8333333333333334,1]]]]
smallest first     [["ebike",[[2,5],[1,6]]],["pedal",[[0,2],[0,1]]]]
missing value      [["a",[[0,5],[0,2]]],["b",[[5,null],[2,6]]]]
missing value fixed [["a",[[0,5],[0,2]]],["b",[[5,5],[2,6]]]]
negatives, none    [["a",[[0,5],[0,-2]]],["b",[[5,2],[-2,2]]]]
negatives, diverging [["a",[[0,5],[-2,0]]],["b",[[-3,0],[0,4]]]]
no rows            [["a",[]]]
no keys: []