The fleet as a treemap with labels that fit
Four rectangles are too small for their names. In the picture they keep a tooltip (hover to see it).
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
station rectangles: 25 | labelled: 21 | too small for a label: Rope Walk, Clock Tower, Station Road, West Gate
biggest: Market 102x93 (20 bikes) | smallest: Clock Tower 43x62 (6 bikes)
area ratio 3.6 | bikes ratio 3.3 (rounding to whole pixels moves it a little)
every station inside its district: true | tiling: squarify (the default)