A hierarchy from the fleet, and what sum does with awkward data
value on a node is the sum of its leaves. Quay has 5 e-bikes and 8 pedal bikes, so 13.
Some data is boxes inside boxes: a fleet is split into districts, stations and bike types. d3.hierarchy wraps that data in nodes, sum adds the values up, and a layout (treemap, pack, partition or tree) gives every node a position and a size.
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.
Make the treemap show the e-bike share of each station as a second colour: a darker rectangle at the bottom of each cell, with a height proportional to the e-bikes.
Write labelFits(node, fontSize) that returns true only if the node's rectangle is wide and tall enough for its name, using getComputedTextLength of a temporary text element.
Explain it without notes
What does d3.hierarchy return, and what does sum add?
How is the data of a treemap different from the data of a force layout?
Why is the node's label dropped when a rectangle is small, and what keeps the information reachable?
A chart has twelve levels of nesting with padding at each level. What goes wrong?
Preview
Console
Nothing logged yet.Expected console output
bikes in the fleet: 320 | nodes: 82 | leaves: 50 | height: 3
districts by bikes: Harbour 71, Old Town 62, University 50, Westpark 47, Riverside 46, Hillcrest 44
a leaf's path: Lumen Bikes > Harbour > Quay > ebike | depth 3 | value 5
Quay's children: pedal 8, ebike 5 | descendants of Harbour: 16
odd tree: total 3 | leaves: 5 | empty list=0, no value=0, text=0, zero=0, three=3
a node with children: [] is a leaf: true
stratify: all@0 a@1 b@1 a1@2
multiple roots