Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 44 ยท Projects and Practice

Project: An Animated Bar Chart Race

Build a bar chart race in D3: rank items per period, interpolate keyframes, animate sorted bars with transitions, add value labels, a ticking date and replay controls.

A "bar chart race" shows how a ranking changes over time: bars grow, overtake each other and swap places as the clock advances. It looks flashy but it uses only ideas you already know: a data table by period, a rank for each item, a keyed join and a chain of transitions. It also teaches an important technique: keyframes, extra interpolated states between data points, so the motion is smooth even when the data has only one value per period.

Plan

flowchart LR
  D["Values per period"] --> K["Keyframes: interpolate between periods"]
  K --> R["For each frame: sort and keep top N"]
  R --> J["Keyed join: bars, labels, values"]
  J --> T["Linear transition per frame"]
  T --> K2["Next frame"]

Each frame is a snapshot; chaining short linear transitions between snapshots makes the animation.

  1. Data. A table of values per period. We have 8 items and 10 years of made-up popularity scores (generated with a formula, not real statistics).
  2. Keyframes. For two neighbouring periods a and b, create k frames with values mixed linearly, like d3.interpolateNumber(a, b)(i / k).
  3. Ranking. In each frame sort descending and assign rank. Keep the top n visible; items outside the top ranks get rank = n and fade out below the chart.
  4. Drawing. One bar per name with a key function. Per frame, transition the vertical position (from rank), the width (from value) and the text.

Interpolating keyframes

JavaScript
function keyframes(periods, k) {
  const frames = [];
  for (let p = 0; p < periods.length - 1; p++) {
    const a = periods[p], b = periods[p + 1];
    for (let i = 0; i < k; i++) {
      frames.push({
        label: a.label,
        values: a.values.map((v, j) => v + (b.values[j] - v) * (i / k))
      });
    }
  }
  frames.push(periods[periods.length - 1]);   // the final state
  return frames;
}

A larger k gives smoother growth and rank swaps (the bars cross smoothly because rank is computed per frame), at a cost in running time. Six frames per period at 60 ms per frame is about a third of a second per period.

The race

Bar chart race

Press Replay while it is running: the running counter makes the old loop stop at its next frame, so two races never fight over the same bars.

Walking through the code

  • rankFrame sorts a frame and writes rank. Names outside the top n get the same rank n and fade out; when they climb into the top they fade in.
  • The x scale is rebuilt every frame from the current maximum, so the leader always fills the width. Some races use a fixed maximum instead; the top bar then grows slowly and looks more honest about absolute growth. Decide which message you want.
  • Linear easing between frames, because each frame is already a small step: easeLinear joins them seamlessly. The default cubic easing would stutter at every frame boundary.
  • All transitions are created from one svg.transition() (t). Sharing it keeps the timing of position, width and label identical.
  • The year label is a big, light-grey text in the corner, a common design choice that does not compete with the bars.

Making it better

  1. Format the values (d3.format(",")) and add the unit.
  2. Show an axis at the top with ticks that fade as the scale changes.
  3. Add a play/pause button using a flag checked in the loop.
  4. Use d3.timer with the elapsed time for exact timing instead of setTimeout.
  5. Show "top 10" instead of "top 5" and shrink the bar height to match.
  6. Let the user scrub with <input type="range"> bound to a frame index and call draw(frames[i], 0).
  7. Replace the made-up numbers with your own CSV and reshape it from long to wide (Loading and Cleaning Data).

Common mistakes

  • No key function: bars get re-assigned to different names each frame and the animation jumps.
  • Dropping items outside the top: they must still exist (with a hidden rank) or they pop into existence instead of sliding in.
  • Starting a new race without cancelling the previous loop.
  • Choosing cubic easing for per-frame transitions.
  • Sorting the original array in place: build new row objects first, as rankFrame does.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is a keyframe in this project?

    Interpolating values creates intermediate frames, so the ranking changes gradually.
  2. 2. Why use d3.easeLinear for each frame's transition?

    Easing every tiny step would slow down and speed up at every boundary and look jerky.
  3. 3. Why does the join use a key function d => d.name?

    Without keys, elements are matched by index and would belong to different items every time ranks change.
  4. 4. How does the code stop an older race when Replay is pressed?

    Each play() call captures its own id; if the global counter moved on, the old loop ends at the next frame.

Summary

  • A bar chart race is keyframes plus sorting plus a keyed join plus short linear transitions.
  • Interpolate values between periods to make rank swaps smooth.
  • Rebuild or fix the scale depending on the message you want to send.
  • Guard long-running animation loops against overlapping runs.

Next: Project: A Drill-down Treemap