Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 10.5 — Responsive Charts
Data Visualization · Example 3 of 3

One chart, three widths, and the size class decisions

In the picture: three charts of the year's rides, 320, 600 and 1000 pixels wide, drawn one above the other with the same data. The widest has a label for every month, the others fewer. A width of 0 (a hidden box) and NaN (unknown) get the small layout. At 479 pixels the layout is small, at 480 medium: the boundary is exact, and the rule width >= 480 is why NaN falls to small.

A chart can scale (one drawing, stretched by its viewBox) or redraw (a new drawing at the real width). Scaling is free but shrinks the text. Redrawing keeps text readable and lets you choose fewer ticks and shorter labels, at the cost of watching the box with a ResizeObserver, and of not redrawing on every pixel.

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

Write onWidthClass(element, callback) that calls callback(cls) only when the size class changes (small, medium, large), using ResizeObserver and the sizeClass function.

02

The stations bar chart has fixed 20 pixel rows. At 300 pixels wide, which part of it breaks first, and what would you change in drawStationsBar?

Explain it without notes

01

When is scaling with the viewBox enough, and when should a chart redraw?

02

Why use a ResizeObserver instead of window.resize?

03

How does onResize avoid a redraw on every frame of a drag?

One chart, three widths, and the size class decisions

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

drawn at 320 -> small layout, 9 ticks in all
drawn at 600 -> medium layout, 17 ticks in all
drawn at 1000 -> large layout, 17 ticks in all
--- the decisions at the edges of the classes, and for odd widths
   0 small  month label every 3 month(s), y ticks 4
 320 small  month label every 3 month(s), y ticks 4
 479 small  month label every 3 month(s), y ticks 4
 480 medium month label every 1 month(s), y ticks 5
 899 medium month label every 1 month(s), y ticks 5
 900 large  month label every 1 month(s), y ticks 5
1920 large  month label every 1 month(s), y ticks 5
 NaN small  month label every 3 month(s), y ticks 4