53 min read

Ray had the chart open before anyone else joined the Sector Four call. It was the standard gap-to-leader plot for the 2025 Japanese Grand Prix: twenty coloured lines, the leader pinned to zero at the top, everyone else fanning out below.

Chapter 25 — F1 Data Visualization: Speed Traces, Track Maps, Gap Charts, and the Visuals That Tell Racing Stories

Ray had the chart open before anyone else joined the Sector Four call. It was the standard gap-to-leader plot for the 2025 Japanese Grand Prix: twenty coloured lines, the leader pinned to zero at the top, everyone else fanning out below.

"Look at lap 22," he said. "Verstappen drops eleven seconds off the lead. Then he gets it all back by lap 32. Some recovery."

Ines squinted. "Did he spin? I don't remember a spin."

"He didn't do anything," said Aisha, who had built the chart. "He pitted. Antonelli hadn't stopped yet, so for ten laps the 'leader' was a Mercedes on old mediums. The line measures Verstappen against whoever leads. When the leader changes, the zero changes, and the line bends."

That is the whole chapter in one exchange. The chart was correct: every number on it came from the timing data. It still told Ray a story that never happened. In the book's data snapshot, Verstappen led laps 2–21 and 32–53 of that race, Andrea Kimi Antonelli led laps 22–31 while the front-runners' stops played out, and Verstappen's own "gap to leader" line peaks at 11.033 s on lap 22. No car took a second off Verstappen on track all afternoon.

Aisha redrew it in five minutes. Same data, different question. Instead of "how far behind the leader is everyone?", the race was really asking "could Norris ever get at Verstappen?". So the new chart measured the gap to Verstappen, drew only Norris and Piastri, greyed out the stop laps and shaded the 1-second band where an attack becomes possible. Now the race was easy to read. On the 49 racing laps outside the stop window (laps 2–19 and 23–53), Norris ran between 1.035 s and 2.551 s behind (median 1.515 s). He was never inside 1 s. Verstappen took the flag 1.423 s ahead (official classification), having taken pole the day before by 0.012 s, the Anchor A lap we took apart in Chapter 19.

Twenty-four chapters in, we have drawn hundreds of charts: speed traces, track maps, race traces, stint bars, degradation scatters. This chapter is not a gallery of new analyses. It is about design: the decisions that make a correct chart read correctly. What question does the chart answer? What is its reference? Which colours can a colour-blind reader tell apart? Does the axis start where honesty requires? Where does the eye land first, and is that where the story is? Every principle here is shown as a real before-and-after, built on the book's data, and every fix ends up as a function in boxbox.viz.

🏎️ Fan Track: Read 25.1–25.3 and 25.5. You will learn to read a broadcast graphic critically, and you will see why the "gap to leader" graphic so often lies during pit stops. The code is optional.

📊 Analytics Track: Everything, with the scripts open. 25.2 gives you a colour checker you can run on any palette, and the Project Checkpoint wires the charts to the simulator's output for Chapter 27.

🎮 Sim Racer Track: 25.4 is yours. It covers telemetry overlays, delta traces, track maps and why a rainbow colour scale hides your braking points.


25.1 The question comes before the chart

Every F1 chart answers a question, whether its author chose one or not. The default gap chart answers "how far behind the car in P1 is each car, at each line crossing?". That is a fine question in a race with no stops. In a race with a stop cycle it answers something nobody asked: "how far is each car behind whichever car happens to be in front during the stops?".

Before: the toolkit's default gap-to-leader chart for the 2025 Japanese GP, all twenty cars

📊 Figure (described): The toolkit's default gap chart for the 2025 Japanese Grand Prix: twenty team-coloured lines, gap to the race leader on an inverted y axis from 0 to about 105 s. Around laps 20–32 every line jumps and kinks: Verstappen's line drops to 11 s behind the leader on lap 22 while Antonelli, who had not stopped, led. The chart is accurate, but its reference moved, so its biggest visual event is an artefact of pit timing.

After: gap to Verstappen for Norris and Piastri, with the stop laps greyed and the 1-second attack band shaded

📊 Figure (described): The same race as the gap to Verstappen (the blue zero line) for Norris (solid orange) and Piastri (dashed orange, the second McLaren). A grey band marks the stop window, laps 20–22, and triangles mark the one lap whose gap falls off the scale. A pale blue band from 0 to 1 s shows where an attack becomes possible. Norris's line never enters it: on every racing lap he is 1.0–2.6 s behind, and the shape of the race is a long stand-off rather than a chase.

The second chart is not better because it is prettier. It is better because it has a reference that matches the question.

📐 Definition: The reference of a gap chart is the quantity every line is measured against. The F1 options are: the car leading on that lap (reference="leader"), a car lapping at the winner's average pace (reference="winner_mean", the classic race trace), or a named car (boxbox.viz.pair_gaps(session, "VER", others)). The first moves when the leader changes. The second bends every line under a safety car, because the average includes the slow laps. The third is fixed, so a flat line means "same pace as the reference car".

The fix lives in one small function. Because metrics.gap_to_leader_by_lap gives every car's gap to the same leader at each line crossing, the difference between two cars' gaps cancels the leader out entirely:

def pair_gaps(session, ref, others):
    """Gap (s) of each car in `others` to car `ref` at the end of every lap,
    from line crossings. > 0 = behind ref. A change of leader cancels out."""
    g = metrics.gap_to_leader_by_lap(f1data.session_key(session))
    w = g.pivot_table(index="lap_number", columns="acronym", values="gap_s")
    return pd.concat([pd.DataFrame({"lap_number": w.index, "acronym": o,
                                    "gap_s": (w[o] - w[ref]).to_numpy()})
                      for o in others if o in w], ignore_index=True)

Running code/01_question_first.py prints the numbers the hook used:

  leader VER: laps 2-21
  leader ANT: laps 22-31
  leader VER: laps 32-53
Stop window (first in-lap to last out-lap of VER/NOR/PIA): laps 20-22
NOR gap to VER (s), laps 2-19 and 23-53:
  min 1.035  median 1.515  max 2.551  n laps 49
  laps within 1.0 s: 0
PIA gap to VER: min 1.797  median 2.886  max 4.386
VER's own 'gap to leader' peaks at 11.033 s on lap 22 (while another car led)
Laps where VER's gap to leader > 0: 10

Ten laps of Verstappen "behind the leader" in the default chart, and zero laps of Norris within a second in the redesigned one. The data did not change. The question did.

Matching F1 questions to chart forms

Most of the book's charts fall into a small set of forms. Pick the form from the question, never from what the library makes easy.

The question The form Reference / encoding Built in
Where on the lap is the time? Speed trace + delta panel, distance on x one lap as reference; delta = cmp − ref Ch 19, 23; 25.4
Where on the circuit does a channel change? Track map coloured by the channel sequential scale for magnitude, ordinal for gear Ch 10; 25.4
Who gains where? Track map or bar of segment deltas diverging scale with a neutral middle Ch 19; 25.4
Is the gap opening or closing? Gap chart, lap on x a fixed car, or the leader in a stop-free race Ch 13; 25.1
Who climbed and fell? Position ("spaghetti") chart focus + grey context, or small multiples Ch 17; 25.5
What did each car run? Stint (strategy) bars compound colour + letter Ch 12; 25.5
How fast, and how consistent? Distribution (violin, strip, box) every lap visible, median marked, n printed Ch 20; 25.6
How fast do tyres fade? Lap time vs tyre age, one panel per stint or driver shared axes Ch 22; 25.6
How likely is each outcome? Histogram of simulated or historical outcomes common x scale, quantiles in text Ch 27; Checkpoint

⚠️ Common pitfall: the gap-to-leader chart in a race with stops. Whenever the leader pits, every other car's line jumps by about a pit loss (a green-flag median of 22.512 s across 1,921 stops in 2023–26; see Chapter 12). The jumps look like dramatic gains and losses. They are the reference moving. Use a fixed car, or grey out the stop window and say why.

🔄 Check your understanding 1. In the default chart, Verstappen's line sits at 11.033 s on lap 22. What would his line show on lap 22 in a chart of the gap to Verstappen? 2. Why does a difference of two gaps-to-leader not depend on who the leader is?

Answer 1. Zero on every lap: he is the reference. 2. At lap L both gaps are measured from the same moment, the leader's crossing of the line on lap L. Subtracting one from the other removes that moment and leaves the time between the two cars' own crossings.


25.2 Colour that carries identity, and the readers it fails

Formula One has a ready-made categorical palette: team colours. OpenF1 publishes one hex code per team per session (f1data.team_colors(session)), and the toolkit uses it everywhere, with the team's second driver dashed (plots.driver_styles). That convention is good for fans, who already know that orange means McLaren. But a team colour was chosen for a car, not for a chart, and two jobs it was never designed for matter a great deal on a page.

  1. Contrast against the background. A thin line has to stand out from a white page.
  2. Separation from the other colours, including for readers with a red–green colour-vision deficiency (CVD), which is common, especially among men. You will not know which of your readers have it, so design as if some always do.

Both are computable. We don't have to guess whether two colours "look different enough".

The physics of a colour difference

Contrast ratio comes from the WCAG 2.x accessibility guidelines. First linearise each sRGB channel $c \in [0,1]$:

$$c_{lin} = \begin{cases} c/12.92 & c \le 0.04045 \\ \left(\frac{c+0.055}{1.055}\right)^{2.4} & \text{otherwise}\end{cases}$$

Then take the relative luminance $Y = 0.2126R + 0.7152G + 0.0722B$ (on the linear values), and form

$$\text{contrast} = \frac{Y_{\text{lighter}} + 0.05}{Y_{\text{darker}} + 0.05}.$$

In plain English: contrast is the ratio of how much light the two colours send to your eye, with a small offset for screen glare. It runs from 1 (identical) to 21 (black on white). For graphical objects such as chart lines, WCAG 2.1 (success criterion 1.4.11, non-text contrast) asks for at least 3:1. Worked number: Mercedes's 2025 OpenF1 colour #27F4D2 has $Y \approx 0.70$, so its contrast on white is $(1.00 + 0.05)/(0.70 + 0.05) = 1.40$, less than half the target.

Colour difference is best measured in a space built so that equal distances look equally different. We use OKLab (Björn Ottosson's perceptual colour space), where $L$ is lightness and $a, b$ are the green–red and blue–yellow axes. The difference is the Euclidean distance, scaled by 100:

$$\Delta E = 100\sqrt{(L_1 - L_2)^2 + (a_1 - a_2)^2 + (b_1 - b_2)^2}.$$

In plain English: $\Delta E$ is how far apart two colours sit in a space shaped like human vision. Below about 6, two thin lines are hard to tell apart; 6–8 works only with a second cue such as a dash or a marker; 8 or more is comfortable. For readers with full colour vision we want even more, 15 or above, because two neighbouring lines in a busy chart need a margin. These are working thresholds from data-visualisation practice, not laws of physics, and the chapter uses them consistently.

Colour-vision deficiency can be simulated. Machado, Oliveira and Fernandes (2009) derived 3×3 matrices that map linear RGB to what a person with protanopia (no long-wavelength cones), deuteranopia (no medium-wavelength cones) or tritanopia sees. At full severity, deuteranopia is

$$\begin{pmatrix}R'\\G'\\B'\end{pmatrix} = \begin{pmatrix}0.367 & 0.861 & -0.228\\ 0.280 & 0.673 & 0.047\\ -0.012 & 0.043 & 0.969\end{pmatrix}\begin{pmatrix}R\\G\\B\end{pmatrix}.$$

In plain English: the red and green channels get blended together, so colours that differ only along the red–green axis collapse onto the same yellow-brown. Worked number: Ferrari's 2025 red #E80020 and Aston Martin's green #229971 are $\Delta E = 33.8$ apart for full colour vision and only 10.0 apart after the deuteranopia matrix. They are still distinguishable, but a third of their difference has gone.

boxbox.viz implements all three in a few lines of NumPy, with no new dependency:

def delta_e(c1, c2, kind=None):
    """OKLab distance x 100, optionally after a CVD simulation ('deutan', 'protan', 'tritan')."""
    return float(100 * np.linalg.norm(_oklab(_sim_linear(c1, kind)) - _oklab(_sim_linear(c2, kind))))

def palette_report(colors, surface="#ffffff"):
    """Per colour: contrast vs surface. Every pair: Delta E for normal vision, deuteranopia and
    protanopia, and a verdict: 'ok' (worst >= 8 and normal >= 15), 'needs 2nd cue', 'collides' (< 6)."""

🔍 Why this works: Colour has three dimensions: lightness, and two hue-and-saturation axes. Red–green deficiency removes most of one hue axis, but it leaves lightness almost untouched. Two colours that differ in lightness survive the simulation; two that differ only in hue do not. That is why a sequential map that runs dark to light reads for everyone, and why "red versus green" is the most fragile pairing in data visualisation.

The audit: OpenF1's team colours, 2023–2026

code/02_colour_audit.py runs palette_report on each season's team colours (taken from that season's Japanese GP so the four years are comparable):

Season summary:
 year  teams  below_3to1  pairs  collides  needs_2nd_cue     worst_pair  worst_dE lowest_contrast
 2023     10           4     45         4              8  haas-mercedes       1.0 mercedes 1.79:1
 2024     10           6     45         0              9 mclaren-sauber       7.1 mercedes 1.40:1
 2025     10           6     45         0              9 mclaren-sauber       7.1 mercedes 1.40:1
 2026     11           5     55         4              5   audi-ferrari       0.9 mercedes 1.84:1

In 2025, six of the ten team colours fail 3:1 on a white page: Mercedes (1.40:1), Kick Sauber (1.70), Williams (1.93), Haas (1.95), McLaren (2.52) and Racing Bulls (2.95). That is the majority of the grid. In 2026 two new teams arrived, and with them the worst pair the audit has found: Audi #F50537 and Ferrari #ED1131 are 1.7 apart for full colour vision, effectively one red. Under deuteranopia they are 1.4 apart, under protanopia 0.9.

2026 team colours as swatches under normal vision, simulated deuteranopia and simulated protanopia, with hex codes and contrast ratios

📊 Figure (described): The eleven 2026 team colours in three columns of swatches: as published, as simulated for deuteranopia, and as simulated for protanopia, with each hex code and its contrast on white. Audi and Ferrari are the same red in the first column and the same olive in the other two. Under both deficiencies McLaren's orange turns mustard, Aston Martin's green turns grey-brown, and Mercedes turns pale grey. Five colours are flagged in red text as below 3:1 on white: Mercedes 1.84, Haas 2.66, Racing Bulls 2.77, McLaren 2.82 and Alpine 2.89.

The twelve closest 2026 team-colour pairs as a dot plot of Delta E under three vision types

📊 Figure (described): One row per team pair, ordered by its worst-case Delta E. For each pair there are three markers: normal vision (black dot), deuteranopia (blue square) and protanopia (orange triangle), on a 0–40 scale with a red band below 6 ("collide") and an amber band from 6 to 8 ("needs a second cue"). Four pairs fall in the red band for some readers: Audi–Ferrari (all three markers under 2), Alpine–Racing Bulls, Cadillac–Aston Martin and Cadillac–Haas. Pairs such as McLaren–Aston Martin look far apart in normal vision (27.1) but drop to 8.7 under protanopia.

The 2026 grid adds three more collisions to Audi–Ferrari. Alpine and Racing Bulls are two light blues 7.4 apart in normal vision and 3.3 under deuteranopia. Cadillac #909090 is a mid-grey, 4.8 from Haas's grey #9C9FA2 even for full colour vision, and under deuteranopia it also merges with Aston Martin's green (5.0), because that green loses its hue and keeps only its lightness.

🧩 Productive struggle: Before reading on, design a lap-by-lap position chart for the 2026 Las Vegas GP that shows Hamilton, Leclerc (Ferrari), Hülkenberg and Bortoleto (Audi), who finished 7th, 10th, 11th and 12th. You must keep team colours, because the audience expects them. What else can carry "which team" and "which driver"? Sketch it, then compare with Figure 25.4.

Ferrari and Audi in the 2026 Las Vegas GP: four panels, before and after, under normal vision and simulated deuteranopia

📊 Figure (described): Four renderings of the same position chart for HAM, LEC (Ferrari) and HUL, BOR (Audi), with the safety-car laps shaded. Top row: colour only, as normal vision and as simulated deuteranopia. All four lines are the same red (or the same olive), and the legend cannot help. Bottom row: the fix. Team-mates differ by line style (solid and dashed), the two teams differ by marker (circles for Ferrari, diamonds for Audi), and every line ends in a direct label naming driver and team. The fixed chart reads the same under deuteranopia as in full colour.

The fix uses three redundant cues, and none of them is colour:

  • Line style separates team-mates. That is the toolkit convention (driver_styles: the higher car number is dashed).
  • Marker shape separates teams that share a hue.
  • Direct labels at the line ends replace the legend, so the eye never has to match a colour to a key.

⚠️ Common pitfall: a colour-only legend. A legend asks the reader to remember a colour and find it again in the plot. That is the hardest possible task for a colour-blind reader, and it is slow for everyone else. If there are four lines or fewer, label them directly at their ends and keep the legend only for categories that have no line end, such as the SC shading.

The audit also explains a chart we have already met. The Miami 2026 undercut chart in Chapter 13 drew Antonelli's gap in Mercedes teal. At 1.84:1 on white, that line is legible because it is thick and alone on the page. Put it in a twenty-line chart and it is the first line to disappear. Contrast matters most where marks are thin and crowded.

🔄 Check your understanding 1. Haas #B6BABD and Mercedes #27F4D2 were 9.9 apart in normal vision in 2023 but only 1.0 under deuteranopia. Which colour dimension were they relying on? 2. Why can't a chart fix a team-mate pair (identical colours, $\Delta E = 0$) by choosing a "slightly different" shade for the second driver?

Answer 1. Hue. Their lightness is almost the same (OKLab L about 0.79–0.80), so once deuteranopia removes the green–red difference there is nothing left to separate them. 2. A shade close enough to read as "the same team" is by definition too close to separate two thin lines: the difference would sit far below the ΔE ≈ 8 that thin lines need. Use line style or markers, which do not depend on colour vision at all.


25.3 Honest axes: zero, windows and outliers

A chart's axes are a contract with the reader. The length of a bar promises a quantity. The position of a point on a scale promises a value. The top of the panel promises "ahead" or "faster". F1 data makes it unusually easy to break that contract by accident, because the numbers we care about are tiny differences between big numbers: a 0.3 s gap on a 91 s lap is 0.33 %.

Bars promise length

Take the race pace of the top ten at the 2025 Japanese GP: each driver's median fuel-corrected clean lap (metrics.race_pace). code/03_honest_axes.py prints it:

acronym team_ref  n_laps  pace_s  gap_s  gap_pct
    PIA  mclaren      50  90.973  0.000    0.000
    VER red_bull      50  90.986  0.013    0.015
    NOR  mclaren      50  91.003  0.030    0.034
    RUS mercedes      50  91.237  0.264    0.290
    LEC  ferrari      50  91.262  0.289    0.318
    ANT mercedes      50  91.335  0.363    0.398
    HAD       rb      50  91.486  0.513    0.564
    HAM  ferrari      50  91.529  0.556    0.611
    ALB williams      50  91.586  0.613    0.674
    GAS   alpine      50  91.821  0.848    0.932

🧪 Assumption in these numbers: the fuel correction is the toolkit default, 100 kg of start fuel and 0.03 s per kg, a labelled assumption (Chapter 20 and Chapter 22 discuss the data-driven alternative). It shifts every driver's laps by the same amount, so the gaps between drivers barely depend on it.

There are three ways to draw these ten numbers.

Race pace three ways: bars from zero, bars cut at 90.9 s, and gap-to-best dots with bootstrap intervals

📊 Figure (described): Three panels of the same ten drivers. A: bars of median lap time from zero to 100 s. All ten bars look identical. B: the same bars with the axis starting at 90.9 s. Gasly's bar is now about 13 times Piastri's, although his lap was 0.93 % slower. C: gap to the best median as a dot, with a horizontal bar for the bootstrap 95 % interval of each median and the gap and n printed beside it. Piastri, Verstappen and Norris sit within 0.03 s of each other with heavily overlapping intervals, and Antonelli's wide interval reaches back to zero.

Panel A is honest and useless: lap times from zero hide every difference that matters. Panel B is useful and dishonest: a bar's length is the quantity, and starting the axis at 90.9 s makes Gasly's bar 12.7 times Piastri's when the ratio of their lap times is 1.0093. One way to put a number on that distortion is the ratio of the effect shown to the effect in the data:

$$\text{distortion} = \frac{\text{(bar ratio)} - 1}{\text{(data ratio)} - 1} = \frac{12.7 - 1}{1.0093 - 1} \approx 1{,}260.$$

In plain English: the truncated chart exaggerates the difference between Gasly and Piastri by a factor of about twelve hundred. Panel C fixes it by changing the quantity, not the axis. A gap has a meaningful zero (the fastest car), so its bars or dots can start at zero honestly, and the reader's eye compares the right thing.

Panel C also adds what A and B cannot show: uncertainty. The bootstrap intervals (metrics.bootstrap_ci, 10,000 resamples, seed 42; Appendix E explains the method) say that the order of the top three is not settled by these laps:

acronym  gap_s     lo    hi
    PIA  0.000 -0.116 0.148
    VER  0.013 -0.046 0.070
    NOR  0.030 -0.029 0.094
    RUS  0.264  0.189 0.356
    ...
    ANT  0.363 -0.005 0.486
Intervals overlapping the fastest driver's interval: ['VER', 'NOR', 'ANT']

"Piastri had the best race pace" is what the numbers say. "Piastri, Verstappen and Norris were indistinguishable on race pace" is what the chart should say.

📐 Definition: A quantity has a meaningful zero when zero means "none of it": a gap, a time loss, a count, a share. Bars may only encode quantities with a meaningful zero, and their axis must start there. Lap times, speeds and temperatures have no useful zero for comparison, so draw them as points or lines on a window, or convert them to gaps first.

Windows promise relevance, and outliers must stay visible

Lines and dots don't need a zero. They need a window that shows the variation the story is about. Here the trap runs the other way: one huge value stretches the axis and flattens everything else.

Verstappen and Norris lap times: auto-scaled with the out-laps setting the axis, versus a window on the racing laps with off-scale laps marked

📊 Figure (described): Two panels of Verstappen's and Norris's raw lap times at the 2025 Japanese GP. Left: matplotlib's automatic scale runs from 90 to 115 s because the two out-laps took about 114 s, so the 53 laps of racing are squeezed into a flat band. Right: the y window covers the racing laps (about 90.6–94.5 s). The lines break at the off-scale laps, small triangles on the top edge mark them, and a note gives their true times (lap 1 NOR 96.1, VER 95.1; lap 21 in-laps NOR 95.0, VER 95.2; lap 22 out-laps NOR 114.8, VER 114.1). The fuel-burn trend and the step at the tyre change are now visible.

Clean laps VER+NOR: n=100, min 91.041, max 93.947, range 2.906 s; all laps range 23.756 s

The racing signal lives in a 2.9 s range; the full data span 23.8 s. Auto-scaling gives the 21 s of pit-stop noise 88 % of the panel. viz.clip_view sets the window and keeps the excluded points on the chart as edge markers:

def clip_view(ax, x, y, lo, hi, ..., inverted=False):
    """Set the y window to [lo, hi] WITHOUT dropping data: points above hi are drawn as arrows on
    the top edge (optionally labelled with their true value), points below lo on the bottom edge."""

⚠️ Common pitfall: dropping the outliers instead of clipping the view. If you delete the pit laps from the data and draw a line, matplotlib joins lap 20 to lap 23 with a straight segment. That segment is a fabricated lap time: it shows the car "doing" lap 21 at an interpolated pace it never ran. The toolkit's gap_chart warns about exactly this in its source (max_gap_s clips the view and never drops points). Break the line (set the value to NaN so the line has a gap) and mark the excluded laps.

Direction promises "ahead"

Two F1 conventions run against matplotlib's defaults, and both are worth keeping.

  • Position charts put P1 at the top. Position 1 is the smallest number, so the y axis has to be inverted.
  • Gap charts and race traces put "ahead" at the top too, so a car that gains moves up. The book's helpers invert the axis and say so in the label ("up = ahead").

Whatever you choose, choose it once, write it in the axis label, and never mix conventions on one page. And as the toolkit's house rules insist, never use a second y axis. Two scales on one panel let the author line up any two curves they like. If you need lap time and gap on the same laps, stack two panels on a shared x axis, as Figure 25.17 will.

📺 On the broadcast: The TV gap graphic ("+1.4") is a gap to the car ahead, refreshed at each timing loop, and it suffers from both problems in this section. During a stop cycle the car ahead changes, so the number jumps by a pit loss. And the graphic shows one number with no history, so a gap that is closing at 0.1 s a lap looks the same as one that is opening. When a commentator says "he's reeling him in", ask for the chart behind it: the gap to a fixed car over the last ten laps.

🔄 Check your understanding 1. Why is a bar chart of "gap to pole (s)" honest when a bar chart of "lap time (s)" from 90 s is not? 2. A colleague removes the safety-car laps from a lap-time line chart "to make it cleaner". What has the chart now shown that never happened?

Answer 1. Pole is a meaningful zero for a gap, so bar length is proportional to the quantity. A lap-time bar cut at 90 s encodes "lap time minus 90 s", a quantity nobody defined. 2. Straight line segments that bridge the removed laps, i.e. invented lap times at an interpolated pace. Break the line instead, and shade or mark the SC laps.


25.4 Telemetry charts: Anchor A, redesigned

Telemetry is where F1 charts are at their most beautiful and their most over-confident. The speed trace is the sport's signature visual. But our telemetry samples at about 3.7 Hz, distance is integrated from speed rather than measured, and two laps have to be aligned before they can be compared (see Chapter 2 and Chapter 19). A well-designed telemetry chart shows the signal and the limits of the instrument.

On Verstappen's 2025 Suzuka pole lap, telemetry_tools.sampling_stats reports:

sampling VER: {'samples': 325, 'median_dt_s': 0.24, 'p95_dt_s': 0.401, 'max_dt_s': 1.04, 'hz': 4.167,
               'median_spacing_m': 16.611, 'p95_spacing_m': 31.792}

That is 325 samples for a 5.8 km lap, one every 16.6 m on median and every 31.8 m at the 95th percentile.

Before: the default overlay

The toolkit's default speed trace for VER and NOR at Suzuka 2025 qualifying, with a uniform-rescaled delta panel

📊 Figure (described): The toolkit's default speed_trace for Verstappen (blue) and Norris (orange): speed against integrated distance, with a delta panel below. The title is generic ("Speed along the lap"), the corners are unnamed, there is no source line, and the delta uses one uniform rescaling for the whole lap. Its sharpest feature is a dip to about −0.26 s at the hairpin that recovers within about 100 m.

The default is a good working chart. As a published figure it has four problems:

  • The title describes the chart instead of stating the finding.
  • The corners are anonymous, so the reader cannot connect a dip to a place.
  • The delta's most dramatic feature, the −0.258 s dip at the hairpin, is an alignment artefact. Chapter 19 showed that anchoring Norris's lap to the official sector lines reduces it to −0.175 s at 2,890 m.
  • Nothing tells the reader which wiggles are real.

After: the story, the places and the noise band

Redesigned Anchor A: speed trace with corner names and sector lines, and a sector-anchored delta with a grey band for the 0.05 s noise floor

📊 Figure (described): The same two laps, redesigned. The top panel names the corners (T1-2, S Curves, Degner 2, Hairpin, Spoon, Casio), marks the two official sector lines and puts the lap times and "pole" in the legend. In the lower panel the delta is sector-anchored, with fills in the leading car's team colour (blue where Norris is behind, orange where he is ahead) and a grey band at ±0.05 s labelled as inside the noise. The title states the finding: the lead changes hands 8 times along the lap, and 65 % of the trace sits inside the noise band.

sector-anchored delta: end +0.012 s, max +0.121 at 770 m, min -0.175 at 2890 m
share of the lap where |delta| <= 0.05 s: 65.1%
sign changes of the delta (|delta| > 0.005 s): 8
stretches with |delta| > 0.05: 405 of 1159 grid points; ranges (m): [(400, 1175), (2450, 2465), (2710, 2935), (2955, 2955), (3740, 3825), (4440, 5335)]

The ±0.05 s band is Chapter 19's working rule: across 564 sector-line predictions in 2025–26 qualifying, the telemetry delta's median error was 0.024 s and its 90th percentile 0.077 s. The band does not say the trace inside it is wrong. It says the instrument cannot vouch for it. Only four stretches clear it in a meaningful way:

  • Verstappen's gain through T1–2 (400–1,175 m);
  • Norris's lead through the hairpin (2,710–2,935 m);
  • a short Verstappen gain into Spoon (3,740–3,825 m);
  • Norris's long lead from Spoon's exit to the Casio Triangle (4,440–5,335 m), which Verstappen erases in the final chicane.

Three design choices did the work:

  1. Fills in the team colour of whoever is ahead. Fill colour tells you who, and the curve's height tells you how much. The curve itself stays black, because it is a quantity, not an identity.
  2. A named noise band. It turns "how big is significant?" from a reader's guess into a stated rule.
  3. A title that is a sentence with a number. Readers who stop at the title still leave with the finding.

📋 Try it: Compare these drivers. Load 2025 Japanese GP qualifying, take Piastri's and Leclerc's fastest laps, and redraw Figure 25.7b for them with boxbox.laptime.delta_trace(..., align="sectors"). Before you plot, predict from the sector table (Ch 19) which sector holds most of the gap. Then report the share of the trace inside ±0.05 s. Expected shape: one row of output per stretch beyond the band, and a title with your share in it.

Track maps: the colour scale is the axis

A track map coloured by speed (plots.track_map) has no y axis. The colour scale is the measurement. So the scale has to do what an axis does: equal steps in data must look like equal steps in colour, and "more" must look like "more".

The same Suzuka lap coloured with jet, viridis and plasma, above a plot of each scale's lightness

📊 Figure (described): Verstappen's pole lap drawn three times, coloured by speed with the rainbow 'jet' scale, viridis and plasma (the toolkit default). Below, a line plot of OKLab lightness along each scale from slow to fast. Viridis and plasma rise steadily from about 0.29 to 0.92–0.94. Jet rises to 0.95 in the middle (the cyan-yellow band) and falls back to 0.38 at the fast end (dark red). On the jet map, 200–250 km/h corners look brighter and more prominent than 320 km/h straights, and sharp hue boundaries appear where the speed changes smoothly.

jet: OKLab L from 0.27 to 0.38, min 0.27, max 0.95, decreasing steps 108 of 255
viridis: OKLab L from 0.29 to 0.92, min 0.29, max 0.92, decreasing steps 0 of 255
plasma: OKLab L from 0.29 to 0.94, min 0.29, max 0.94, decreasing steps 0 of 255

viz.cmap_lightness measures the problem. Along jet, lightness falls in 108 of 255 steps, so 'faster' becomes 'darker' over the top half of the speed range. A reader's eye ranks marks by lightness before it reads hue. So on a jet map the middle speeds shout and the fastest straights recede, and anyone printing the page in greyscale, or seeing it with deuteranopia, loses the order completely. The fix is free: use a perceptually ordered map (viridis, plasma, cividis) for magnitude. Gear is different. It is ordinal (eight ordered steps), so the toolkit's gear map uses eight discrete steps of viridis with a stepped colour bar, never a smooth gradient that invents "gear 4.5".

Diverging data needs a neutral middle

"Who gains where?" is not a magnitude question. It has a sign. One driver gains in some places, the other elsewhere, and in between nobody gains anything measurable. That is diverging data, and it needs a diverging scale: two hues for the two directions, meeting at a neutral grey for "no difference".

Suzuka 2025 track map coloured by where Norris gains or loses time per 100 m, on a diverging orange-grey-blue scale

📊 Figure (described): The Suzuka outline coloured by the rate at which the sector-anchored delta changes over 100 m windows: orange where Norris gains, blue where Verstappen gains, grey where the rate is within ±0.01 s per 100 m. The grey middle covers 37 % of the lap. Orange stretches sit at T1-2's exit, the S Curves, Degner 2, the hairpin exit and Spoon. Blue stretches sit on the run into the hairpin, after Degner 2 and through the Casio Triangle.

The poles are the two teams' colours, Red Bull blue and McLaren orange, and that choice is legitimate here for a reason worth spelling out. A diverging scale needs two hues that read as opposite, and blue against orange is the classic cool–warm pair that survives deuteranopia (it is a blue–yellow contrast after simulation). Had the pair been Ferrari and Audi, team colours could not have been the poles at all.

rate of delta change per 100 m: min -0.112, max +0.147; share of the lap inside +/-0.01: 37.2%

⚠️ Common pitfall: putting a hue at the midpoint. A rainbow or a red–yellow–green scale for "gain/loss" puts yellow at zero, and yellow is the most eye-catching colour on the page. The places where nothing happened become the brightest. A neutral grey midpoint makes "no measurable difference" recede, which is exactly what it should do.

Small multiples: the same lap, four seasons

When the question is "how does this change across seasons, circuits or drivers?", draw small multiples: the same chart repeated in a grid, on identical scales, one panel per case. The eye compares shapes, not legends.

Suzuka pole laps 2023–2026 as four stacked speed traces on one shared scale, with frozen-telemetry stretches shaded red

📊 Figure (described): Four stacked speed traces with a shared distance axis and a shared 50–345 km/h speed axis: Verstappen's poles in 2023 (1:28.877), 2024 (1:28.197) and 2025 (1:26.983), and Antonelli's in 2026 (1:28.778). The 2023–2025 shapes are near-identical. The 2026 panel's title is in red ("FAILS quality check: frozen 25.9 s, distance ×0.928"). Red bands mark a 2.5 s frozen stretch at 449–673 m and a 25.9 s stretch at 4,028–5,387 m, where the trace is a flat line at about 190 km/h through Spoon, the back straight and 130R.

2026 pole ANT 88.778: quality {'frozen_s': np.float64(25.89), 'max_gap_s': 1.08, 'dist_ratio': 0.9278, 'ok': False}; frozen stretches >= 0.5 s: [(449, 673, 2.5), (4028, 5387, 25.9)]

This is the design principle behind Chapter 2's warning, made visible. The 2026 Suzuka pole lap is the reason Anchor A uses 2025. On a single chart, the flat stretch could pass as a lift. In a grid of four, with the three good laps above it, the frozen feed is obvious. Showing a failed quality check is better than silently dropping the panel: the reader learns what bad data looks like.

🔄 Check your understanding 1. Why do the fills in Figure 25.7b use team colours while the delta line itself is black? 2. You want a track map of brake on/off. Sequential, diverging or categorical scale?

Answer 1. Fill colour carries identity (who is ahead), which is a categorical job. The line carries a quantity (how far ahead), which is shown by position on the y axis and needs no colour. 2. Brake is a two-state category in our data (0 or 100), so it needs two clearly different colours, ideally different in lightness as well as hue, with a two-entry legend. A continuous scale would invent intermediate brake pressures we do not measure.


25.5 Race charts: focus, context and the stint bar

The spaghetti problem

A position chart of twenty cars over fifty laps has a thousand line segments and hundreds of crossings. Drawn in full colour, it shows everything and says nothing.

The toolkit's default position chart for the 2026 Las Vegas GP: all cars in team colours

📊 Figure (described): The default lap-by-lap running order for the 2026 Las Vegas Grand Prix: twenty-one coloured lines (team-mates dashed; Albon did not start), the safety-car laps shaded, driver codes at both ends. Several teams' blues and reds are hard to follow through the crossings, and some end labels overlap (LEC and COL both at P6, ALO and BOT at P18).

The fix is focus and context: decide which two or three cars the story is about, draw them in colour with thick lines and direct labels, and draw everyone else in thin grey underneath. The grey field is not decoration. It shows the traffic the focus cars moved through.

Focus and context: Piastri, Sainz and Verstappen in colour against a grey field, 2026 Las Vegas GP

📊 Figure (described): The same race with three cars in colour: Verstappen (solid blue, P1 to P1), Piastri (dashed orange, grid 17 to P3) and Sainz (dashed blue, grid 20 to P8), with "grid to finish" in each end label. The other 19 cars are thin grey lines. Piastri's line climbs steadily from P12 after lap 1 to P5 by lap 33 and P3 at the flag, with a dip during the safety-car stops.

2026 Las Vegas: grid -> finish (Jolpica), biggest movers:
acronym     team_ref  jolpica_grid  jolpica_position  gain jolpica_status
    PIA      mclaren            17                 3    14       Finished
    SAI     williams            20                 8    12       Finished
    BEA         haas            22                13     9       Finished
PIA position by lap (every 5th): {1: 12, 6: 10, 11: 10, 16: 8, 21: 11, 26: 8, 31: 7, 36: 5, 41: 5, 46: 5}

Two details in the redesign come from section 25.2. Verstappen's 2026 Red Bull blue #4781D7 and Sainz's Williams blue #1868DB are only 8.0 apart in normal vision, below the 15 we want for neighbours. They are separated here by line style (Sainz is Williams's second driver, so dashed) and by the direct labels. And viz.focus_lines checks every focus colour against the context grey: a focus colour within $\Delta E < 15$ of the grey, such as Haas #9C9FA2 (13.5) in 2026, is drawn in near-black instead, or it would vanish into the field it is meant to stand out from.

📋 Call the pit stop: 2026 Las Vegas, lap 18. You run Piastri's strategy. He is P8 at the end of lap 16 on softs he started on, about 5–6 s behind Verstappen. On lap 19 the safety car is deployed. The book's measured pit loss under a safety car is 12.722 s (95 % CI 11.02–14.50, n = 137), against 22.512 s under green. Do you stop at the end of lap 19? What do you expect everyone around you to do, and what does that do to your track position?

Reveal The stint data show that 20 cars made a stop, and 16 of them took it on in-lap 19, with two more on lap 20, one on lap 18 and one on lap 1. Piastri stopped with them, from SOFT to MEDIUM, and ran to the flag. When everyone takes the cheap stop, nobody gains track position from the stop itself. Piastri was P9 after lap 18 and P8 after lap 26, and his climb to P3 came on track over the last 25 laps. The design lesson: in a race where every car stopped on the same lap, the stint chart will look nearly uniform. That is a finding, so put it in the title (Case Study 1 does) rather than leaving a chart that looks as if it shows nothing.

The stint chart: colour plus a letter

Tyre strategy charts are the one place F1 has a fixed colour code, Pirelli's sidewall colours: red SOFT, yellow MEDIUM, white HARD, green INTERMEDIATE, blue WET. The toolkit uses it (plots.COMPOUND_COLORS). It has two built-in accessibility problems:

  • HARD is white, so on a white page its bar is defined only by its edge.
  • SOFT red and INTERMEDIATE green are the classic red–green pair.

Stint charts for the 2025 Japanese GP, before (colour only) and after (letters, in-lap numbers, edges and hatching)

📊 Figure (described): Two versions of the 2025 Japanese GP strategy chart in finishing order. Left: colour-only bars; the HARD stints are pale grey bars with no edge, barely distinguishable from the background grid. Right: viz.strategy_chart. Every bar carries its compound letter (S, M, H), HARD bars have a dark edge, the in-lap of each stop is printed above the boundary, and sets that started the stint already used are hatched (Alonso's and Ocon's first stints and several second stints). Nineteen cars made one stop. Hamilton, Ocon and Bortoleto ran HARD first, and Stroll stopped twice.

2025 Japan: starting sets already used: {'ALO': 1.0, 'OCO': 1.0}
Stops per car: {1: 19, 2: 1}

The letters make the chart readable in greyscale, under any colour-vision deficiency and on a projector that washes out yellow. The in-lap numbers turn a picture into a table you can quote. The hatching shows something colour cannot: whether the set was new. And strategy_chart accepts either a real session or the simulator's strategies (viz.stints_from_strategies), so the race and the model are drawn in the same language. The Project Checkpoint uses exactly that.

🔄 Check your understanding 1. In a focus-and-context chart, why draw the context lines at all instead of only the focus cars? 2. A stint chart of a race in which every car made one stop on the same lap looks almost uniform. Is that a failed chart?

Answer 1. The grey field is the traffic: it shows how many cars a driver passed, where the field was packed and when the order shuffled. Without it a climb from P12 to P3 looks like an empty road. 2. No. Uniformity is the finding ("strategy separated nobody"), so the title should say it. A chart fails when its message is hidden, not when its message is "nothing differed".


25.6 Distributions and small multiples

Show every lap, not just the average

A bar of the mean is the most common way to compare race pace, and it throws away almost everything we know. Each driver ran 50 clean laps at Suzuka. Their spread is information: about consistency, traffic, tyre phases and fuel. And it is the context that tells us whether a gap between two drivers is large.

Race pace distributions for the 2025 Japanese GP top ten: truncated bars of the mean versus violins with every clean lap and the median

📊 Figure (described): Left, "before": ten team-coloured bars of the mean fuel-corrected lap, on an axis cut at about 90.7 s, so Bearman's bar looks about four times taller than Norris's. Right, "after": one violin (a smoothed density outline) per driver in finishing order, every clean lap as a grey jittered point, the median as a black bar and n = 50 printed above each. Every driver's laps spread over roughly 1–2 s, and the violins of neighbouring finishers overlap heavily.

Clean-lap IQR by driver (s): {'VER': 0.262, 'NOR': 0.376, 'PIA': 0.417, 'LEC': 0.465, 'RUS': 0.351,
                              'ANT': 0.759, 'HAM': 0.553, 'HAD': 0.529, 'ALB': 0.644, 'BEA': 0.524}
Median IQR across top ten: 0.495 | median gap between neighbours in finishing order: 0.098

The numbers explain the overlap. The typical interquartile range (IQR: the spread of the middle half of a driver's laps) is 0.495 s, while the typical gap between neighbouring finishers' medians is 0.098 s, five times smaller. Verstappen's laps were the tightest in the top ten (IQR 0.262 s); Antonelli's, split across a long first stint and a short second one, the widest (0.759 s). A chart of means hides both facts. A violin with its points shows them at a glance.

📐 Definition: A violin plot draws the kernel-density estimate of a distribution, mirrored, so its width shows how many laps fell at each time. It invents a smooth shape between the points, so always draw the points as well (when n is in the tens) and print n. Jitter the points sideways only: moving a lap time vertically would change the data.

One stint per panel, not eight stints on one panel

Degradation plots (Chapter 22) compare slopes. Eight stints on one panel means eight overlapping clouds of points, eight fit lines and an eight-line legend.

The toolkit's degradation plot with eight HARD stints overlaid on one panel

📊 Figure (described): Eight drivers' HARD stints from the 2025 Japanese GP on one panel: fuel-corrected lap time against tyre age, eight marker shapes, eight fit lines and a long legend of slopes and intervals that covers part of the data. The points interleave so completely that no single stint can be followed.

Small multiples: one HARD stint per panel on shared axes, each with its slope, interval and n

📊 Figure (described): The same eight stints as a 2 × 4 grid with shared axes. Each panel has one driver's points, one fit line in the team colour, the slope in the title and the 95 % interval and n in the corner. Slopes range from −0.018 s/lap (Hadjar) to +0.031 s/lap (Antonelli, on the shortest stint). With shared axes the level differences between cars are visible as well as the slopes.

HARD-stint degradation (fuel-corrected, toolkit default):
acronym  slope_s_per_lap  ci_low  ci_high  n
    VER            0.011   0.004    0.019 31
    NOR            0.013   0.006    0.020 31
    PIA            0.004  -0.009    0.017 32
    LEC            0.018   0.004    0.031 31
    RUS           -0.006  -0.021    0.008 33
    ANT            0.031   0.015    0.047 21
    HAM            0.014   0.001    0.028 28
    HAD           -0.018  -0.034   -0.002 27

These slopes are small and some are negative. That is the fuel correction at work, not a mistake: as Chapter 22 showed, degradation numbers depend on how much fuel burn you subtract, and with the toolkit's assumed correction several Suzuka HARD stints show no wear at all. The small multiples make that visible honestly, one interval per panel, instead of hiding it in a crowded legend.

⚠️ Common pitfall: small multiples with independent scales. If each panel picks its own y range, every panel looks equally steep and the reader compares shapes that are not comparable. Share the axes (sharex=True, sharey=True). If one case truly needs a different range, give it a different chart, not a different scale in the same grid.

Sector bars, one scale for every panel

The same rule applies to qualifying sectors. Figure 25.15 shows each team's best sector times at Suzuka 2025 as gaps to the best team, one panel per sector plus the best lap, on one shared x scale that starts at zero.

Qualifying sector gaps by team, 2025 Japanese GP, as four panels on one shared scale

📊 Figure (described): Four panels (Sector 1, Sector 2, Sector 3, Best lap) with teams in rows ordered by best lap, each showing a lollipop from zero to that team's gap in its team colour. McLaren is at zero in all three sectors, yet Red Bull is at zero for the best lap, by 0.012 s. Mercedes is almost level in Sector 1 (0.018 s) but loses 0.306 s in Sector 2. Kick Sauber's gap is the largest everywhere, 1.587 s on the lap.

              duration_sector_1  duration_sector_2  duration_sector_3  lap_duration
red_bull                  0.029              0.158              0.036         0.000
mclaren                   0.000              0.000              0.000         0.012
ferrari                   0.148              0.155              0.087         0.316
mercedes                  0.018              0.306              0.076         0.335

McLaren owning all three best sectors and still losing pole looks like a paradox. It isn't one: a team's best sectors came from different laps and different drivers (Chapter 19's "theoretical best"), while pole is one lap. The chart's subtitle says "sectors from any lap" because the design has to carry that caveat, or readers will add the sectors up.

📋 Try it: Analyze this session. Rebuild Figure 25.13 for the 2026 Las Vegas GP race (top ten), and add one design change: sort the violins by median instead of finishing order. Does the order change? Which finishers ran a faster median than a car that finished ahead of them? Expected output: a ten-row table of median, IQR and n, and a sentence for each "out-of-order" pair (traffic and the lap-19 safety car are the usual suspects).


25.7 Interactive charts with plotly, and the static fallback

Some charts have too many lines for any static design: a full race trace with 21 cars is the classic case. An interactive chart lets the reader do the focusing. Hovering shows the details of one point, clicking a legend entry hides a car, double-clicking isolates it, and dragging zooms. The book's stack includes plotly for HTML outputs only. code/06_interactive_plotly.py builds the 2026 Las Vegas GP as the gap to Verstappen for every car:

fig.add_trace(go.Scatter(
    x=d.lap_number, y=d.gap_s, mode="lines", name=a,
    line=dict(color=s["color"], width=2, dash="dash" if s["linestyle"] == "--" else "solid"),
    customdata=np.column_stack([d.team, d.position_end, d.compound, d.tyre_age]),
    hovertemplate=("<b>" + a + "</b> (%{customdata[0]})<br>Lap %{x}<br>Gap to VER: %{y:.1f} s"
                   "<br>Position: P%{customdata[1]}<br>Tyre: %{customdata[2]}, %{customdata[3]} laps old"
                   "<extra></extra>")))
...
fig.write_html(html, include_plotlyjs="cdn", full_html=True, config={"displaylogo": False})
rows plotted: 985 (21 cars x up to 50 laps) -> vegas_2026_race_trace.csv
HTML written: ch25-interactive-vegas-race-trace.html, 57 KB

Open the interactive version: ch25-interactive-vegas-race-trace.html. The file is 57 KB because it loads the plotly.js library from its public CDN when you open it. For a fully offline copy, change include_plotlyjs="cdn" to True; the file then grows to several megabytes.

Interactivity has three rules that are easy to forget:

  1. The tooltip enhances; it never gates. Anything a reader needs must also be readable without hovering, so the script writes the plotted data to code/output/vegas_2026_race_trace.csv. That table view is also the accessible version for screen-reader users.
  2. Every interactive chart needs a static fallback. PDFs, printed pages, e-readers and slide decks cannot run JavaScript. The fallback is not a screenshot of the interactive version. It is a designed static chart that tells the main story.
  3. Interactivity is not an excuse for a bad reference. Here the reference had to change first.

The obvious race trace for Las Vegas was the classic one, the gap to a car lapping at the winner's average pace. It is the before:

Before: the 2026 Las Vegas race trace against the winner's average pace, dominated by the safety car

📊 Figure (described): The race trace with reference "winner's average pace". Every line climbs steadily to about −110 s by lap 18, plunges by about 300 s during the safety car (laps 19–25), then climbs back to near zero by lap 50. Verstappen, Piastri and Sainz are highlighted, but the lines sit on top of each other, and the safety car's V shape is the only visible feature.

winner_mean reference: VER lap 1 -1.9 s, furthest 'ahead' -112.1 s on lap 18, lap 50 +0.0 s

The winner's average lap includes seven safety-car laps, so it is slower than any green lap. Every car therefore appears to "gain" on the reference under green and to lose it all under the safety car. The chart's dominant shape is a property of the reference, not of the race. With the reference fixed on Verstappen, the same data tell the actual story:

After, and the static fallback for the HTML: gap to Verstappen for Norris, Piastri and Sainz

📊 Figure (described): The gap to Verstappen (the blue zero line, labelled as the reference) for Norris (solid orange), Piastri (dashed orange) and Sainz (dashed blue), with the field in grey, the safety car shaded and open circles on the in-laps. Before the safety car Piastri runs 3–7 s behind. After the restart he closes steadily to under 1 s by the final laps, while Norris spends most of the second half within about 2 s, at times under 1 s. Sainz holds about 6 s, then drifts to 12–13 s.

NOR gap to VER outside the SC (laps): min 0.3 on lap 34, lap 1 1.2
PIA gap to VER outside the SC (laps): min 0.8 on lap 49, lap 1 6.0
SAI gap to VER outside the SC (laps): min 5.5 on lap 1, lap 1 5.5

viz.race_trace takes reference="winner_mean", "leader" or any driver's acronym, so the choice is a single argument, made deliberately, and stated in the y-axis label.

⚠️ Common pitfall: the race trace in a safety-car race. The winner's-average reference works beautifully in a green race, where gentle slopes are pace. Add a safety car and the average lap absorbs it, so the whole chart tilts. Either use a fixed car as the reference, or compute the reference pace from green laps only, and say which in the axis label.

🔄 Check your understanding 1. Name two readers for whom the interactive HTML is useless, and what each of them gets instead. 2. In Figure 25.16a every car appears to gain about 110 s on the reference by lap 18. Where did that time come from?

Answer 1. Someone reading a printed or PDF copy (no JavaScript) gets the designed static fallback, Figure 25.16b. A screen-reader user cannot use a hover tooltip and gets the CSV table view. 2. From the reference, not the cars. The winner's average lap includes seven safety-car laps, so it is slower than any green lap, and every car "beats" it under green until the safety car hands the time back.


25.8 One race story, end to end

Everything so far has been one principle at a time. A published figure has to get all of them right at once. Here is the whole process for the race this chapter started with, 2025 Suzuka, written as the checklist we actually followed.

  1. The question. Saturday's pole was 0.012 s. Did Sunday's race ever give Norris a chance to turn that into a win?
  2. The reference. Verstappen. Every gap is measured to him, so his line is the zero.
  3. The forms. The gap over laps answers "a chance?". Lap times answer "was Norris faster?". Stints answer "did strategy offer anything?". All three share one lap axis: stacked panels, never a twin axis.
  4. Colour. Red Bull blue and McLaren orange (ΔE 37.0 for normal vision, 27.8 at worst under protanopia). The two McLarens are separated by line style and marker, and everything is labelled directly.
  5. Axes. The gap window runs from 0 to 6.5 s with the off-scale stop laps marked. The lap-time window covers the racing laps with the outliers kept as triangles. Up means ahead.
  6. Annotation. A handful of notes, each a fact with a number: the pole margin, the stop laps, the official finishing gaps, and "inside 1 s: never".
  7. Source and caveats. The data source, the definitions (line-crossing gaps, raw lap times) and what the bands mean.
  8. Accessibility. Check the figure under simulated deuteranopia (viz.simulate_figure), write the alt text and the described-figure paragraph.

The 2025 Japanese GP as one publication figure: gap to Verstappen, lap times and stints on a shared lap axis

📊 Figure (described): Three stacked panels sharing one lap axis. Top: Norris's (solid) and Piastri's (dashed) gap to Verstappen, with the pale 1-second band empty all race, notes for the 0.012 s pole, the stop laps 20–22 and the official finishing gaps (+1.423 s and +2.129 s). Middle: the three cars' raw lap times in a 91–94.5 s window, the stop laps greyed and off-scale laps marked by triangles; the lines interleave almost lap for lap after the stops. Bottom: the three cars' stints, MEDIUM to HARD, with Piastri stopping one lap earlier.

code/07_race_story.py prints the numbers behind the annotations, and one more that sharpens the story:

NOR racing laps: n=49, within 1.5 s on 23 laps, min 1.035 (lap 2)
Fastest clean lap each: [{'acronym': 'NOR', 'lap_number': 51, 'lap_duration': 91.116}, {'acronym': 'PIA', 'lap_number': 53, 'lap_duration': 91.039}, {'acronym': 'VER', 'lap_number': 52, 'lap_duration': 91.041}]
Final stint, clean laps both: n=31, NOR faster on 18, median NOR - VER -0.013 s

On the 31 laps of the final stint on which both cars ran clean laps, Norris was quicker on 18, by a median of 0.013 s, and never got closer than about 1.1 s. The timing data are consistent with a car that had the pace to stay with Verstappen but not enough of a margin to close and attack. What the data cannot tell us is how much of Norris's pace was held back by running in Verstappen's wake, and how much simply was not there. The chart should show the stand-off and leave that question open.

🔄 Check your understanding 1. Why does Figure 25.17 use three stacked panels rather than one chart with gap on the left axis and lap time on the right? 2. The middle panel shows Norris and Verstappen interleaving lap after lap. Why doesn't that contradict the top panel, where the gap barely moves?

Answer 1. A second y axis lets the scales be lined up arbitrarily, so any two curves can be made to look related. Stacked panels on a shared x axis keep each quantity on its own honest scale and still align them lap by lap. 2. The gap is the running sum of lap-time differences. Differences that alternate in sign and average −0.013 s cancel out, so the gap stays nearly flat. That is the stand-off: equal pace, no progress.


25.9 An accessibility checklist for every chart in this book

Accessibility is not a separate step. Most of it is the same as clarity. But a few checks only happen if you put them on a list.

Check How Tool
Every mark has contrast ≥ 3:1 on the page compute it; darken, outline or label marks that fail viz.contrast_ratio, viz.darken_to_contrast
Series that must be told apart have ΔE ≥ 8 for CVD and ≥ 15 for normal vision run the pair report; add line style or markers where it fails viz.palette_report
Identity is never carried by colour alone dashes for team-mates, markers for shared hues, direct labels plots.driver_styles, viz.focus_lines
The chart survives greyscale and deuteranopia look at the simulated render viz.simulate_figure
Magnitude uses a lightness-ordered scale; signed data use a grey midpoint never jet; viridis, plasma or a two-hue diverging map viz.cmap_lightness
Text is readable at the published size ≥ 7.5 pt for annotations, axis labels with units plots.use_style()
The finding is in words title as a sentence; alt text; a "📊 Figure (described)" paragraph —
Values are reachable without hovering a CSV or a table next to every interactive chart 06_interactive_plotly.py

Case Study 2 tests the most tempting shortcut, "just darken the failing team colours", across four seasons, with a surprising result.


Spaced Review

Answer each question before you open its answer.

From Chapter 19 (Lap Time Analysis). The toolkit's uniform delta put a −0.258 s spike at the Suzuka hairpin; the sector-anchored delta put −0.175 s at 2,890 m. Why do the two alignments disagree most at the slowest point on the lap?

Answer

At 77 km/h a car covers about 21 m per second, so a few metres of distance misalignment become tenths of a second of delta. At 300 km/h the same error is worth far less time. Anchoring at the official sector lines removes most of the accumulated distance error before the hairpin, so the spurious spike shrinks. That is also why this chapter's noise band (±0.05 s) is a minimum, not a guarantee, in the slow corners.

From Chapter 12 (Race Strategy Fundamentals). The green-flag pit loss pooled over 2023–26 is 22.512 s; under a safety car it is 12.722 s. How does that difference explain the shape of the "before" race trace in Figure 25.16a?

Answer

Stops under the safety car cost about ten seconds less than green stops, which is why nearly the whole Las Vegas field stopped on lap 19. With everyone stopping at once, nobody's line jumps relative to the others. The huge V in the winner's-average trace comes from the reference absorbing seven slow laps, not from the stops.

From Chapter 2 (The F1 Data Pipeline). What two quick checks would have caught the frozen 2026 Suzuka pole lap before it reached a chart?

Answer

The longest run of identical speed and rpm samples while moving (25.9 s here, against Chapter 19's 2 s limit), and the ratio of integrated distance to the official lap length (0.928, outside −3 %/+2 %). Both are in boxbox.laptime.quality_check, and Figure 25.10 shows the result.


Project Checkpoint: viz

Aisha's Box Box simulator can now compute a strategy (Chapter 12), an undercut (13), a safety-car hazard (14) and a degradation model (22). From Chapter 26 on it starts producing distributions of outcomes, and those are worthless if they are drawn badly. This chapter adds project/boxbox/viz.py: the design layer between the numbers and the reader.

Colour checks you can run on any palette

  • contrast_ratio(c1, c2="#ffffff") gives the WCAG 2.x contrast ratio.
  • simulate_cvd(hex, kind) and simulate_figure(fig, kind) give a colour, or a whole rendered chart, as seen with protanopia, deuteranopia or tritanopia (Machado et al. 2009, severity 1.0).
  • delta_e(c1, c2, kind=None) and palette_report(colors) give OKLab ΔE for every pair, with a verdict.
  • darken_to_contrast(hex) gives the same hue at a lower lightness, reaching 3:1.
  • cmap_lightness(cmap) checks whether a colour scale is monotone.

Chart helpers

  • focus_lines(...) draws focus lines over grey context, with direct labels and a guard against grey team colours.
  • clip_view(...) sets a window that marks outliers instead of dropping them.
  • source_below(...) places the source line so it never collides with a legend.

Race and simulator charts

  • pair_gaps(session, ref, others) returns gaps to a fixed car.
  • race_trace(session, focus, reference) draws the race trace with any reference: "winner_mean", "leader" or an acronym.
  • strategy_chart(stints, ...) and stints_from_strategies(strategies, total_laps) draw stint bars for real sessions and simulated plans alike.
  • outcome_hist(samples, discrete=False, ...) draws histograms on a common scale, with n, median and 10–90 % range written into the legend.

code/project_checkpoint.py points the module at the simulator. It fits Chapter 12's race model to the 2025 Japanese GP, takes the six fastest modelled strategies and draws them next to what Verstappen ran:

model, inputs = strategy.fit_race_model(s)
top = strategy.optimise(model, max_stops=2).head(6)
strats = {f"#{i + 1} {r.sequence} ({', '.join(map(str, r.stop_laps))})": r.strategy
          for i, r in enumerate(top.itertuples())}
strats["VER actual M-H (21)"] = strategy.Strategy.parse("M-H", [21])
rows = viz.stints_from_strategies(strats, model.total_laps)
fig = viz.strategy_chart(rows, total_laps=model.total_laps,
                         annotate={k: f"+{v:.1f} s" for k, v in costs.items()})
Model: 53 laps, pit loss 23.337 s (n = 21), deg S/M/H 0.046 / 0.032 / 0.011 s/lap (fuel-corrected, toolkit default)
  #1 S-H (13)                  +  0.00
  #2 H-S (40)                  +  0.34
  #3 M-H (13)                  +  0.64
  #4 H-M (40)                  +  1.08
  #5 M-S (30)                  + 13.42
  #6 S-M (23)                  + 13.53
  VER actual M-H (21)          +  1.89

Box Box output: the six fastest modelled strategies for Suzuka 2025 and the winner's actual plan, with modelled costs

📊 Figure (described): Seven stint bars drawn by viz.strategy_chart from simulator output. The six fastest modelled plans for Suzuka 2025 are S-H (stop lap 13), H-S (40), M-H (13), H-M (40), M-S (30) and S-M (23), followed by Verstappen's actual M-H with a lap-21 stop. Each bar is lettered, the stop lap is printed at each boundary, and the modelled cost against the best plan is printed at the right (+0.0 s to +13.5 s; Verstappen's plan +1.9 s). The four best plans sit within 1.1 s of each other.

The chart does what Chapter 12 taught. The modelled cost curve is flat: the four one-stop plans with a HARD stint are within 1.08 s of each other, and the winner's plan is 1.89 s from the model's best, a gap well inside the uncertainty of the inputs. The design makes the flatness visible: same lap axis, same letters, numbers printed rather than implied.

The second half of the checkpoint draws a distribution the simulator will have to reproduce, where front-row starters actually finish, from 1994–2026 Jolpica results:

grid 1: starts 622, wins 308 (49.5%), podium 75.4%, not classified 14.3%
grid 2: starts 621, wins 158 (25.4%), podium 63.4%, not classified 13.5%

Outcome histogram: finishing positions of grid-1 and grid-2 starters, 1994–2026, with DNF as its own bin

📊 Figure (described): Two step histograms on one finishing-position axis (1 to 20, then a separate "DNF" bin), share of starts on y. Grid-1 starters (solid blue, n = 622) win 49.5 % of the time. Grid-2 starters (dashed orange, n = 621) split almost evenly between P1 (25.4 %) and P2. Both have a long tail and a DNF bar of about 14 %. The legend gives n, a median of P2 for both groups and a 10–90 % range of P1 to DNF.

The 308 wins from grid slot 1 match the book's prediction baselines, which Chapter 26 starts from (those count 621 starts; this filter finds 622). When Chapter 27 runs 10,000 simulated races, outcome_hist is the chart that compares the simulated distribution of finishing positions with this real one. A simulator that cannot produce a 14 % DNF bar is not ready to price a strategy. The last block of the checkpoint is a pre-flight colour check for a five-driver chart of the Suzuka race. It flags what we now expect: Norris and Piastri share a colour (ΔE 0, so line style is required), and Russell's Mercedes teal is at 1.40:1 on white.


Chapter Summary

Principles, each with its F1 example and its tool

Principle What goes wrong without it (real example) Fix boxbox.viz / toolkit
Choose the reference from the question Gap to leader: VER "11.033 s behind" on lap 22 at Suzuka 2025 gap to a fixed car pair_gaps, race_trace(reference=…)
Bars only for quantities with a meaningful zero Lap-time bars cut at 90.9 s: Gasly's bar 12.7× Piastri's (true ratio 1.0093) convert to gaps; dots + intervals metrics.bootstrap_ci
Clip the view, never the data Out-laps (114 s) flattened a 2.9 s signal window + edge markers + broken lines clip_view
Contrast ≥ 3:1 6 of 10 team colours fail in 2025 (Mercedes 1.40:1) darken, thicken or label contrast_ratio, darken_to_contrast
ΔE ≥ 8 for CVD, ≥ 15 normal Audi–Ferrari 2026: ΔE 1.7 dashes, markers, direct labels palette_report, simulate_figure
Ordered scales for magnitude jet's lightness falls in 108 of 255 steps viridis / plasma cmap_lightness
Grey midpoint for signed data yellow-at-zero makes "no difference" the loudest colour two-hue diverging map Fig. 25.9 recipe
Show the instrument's limits 65.1 % of the Anchor A delta inside ±0.05 s named noise band Ch 19 rule
Show distributions, not means neighbour gap 0.098 s vs lap IQR 0.495 s violin + points + n Fig. 25.13 recipe
Small multiples share scales independent scales make every stint look equally steep sharex, sharey Fig. 25.14b, 25.15
Interactive needs a static fallback and a table PDF readers see nothing designed PNG + CSV 06_interactive_plotly.py

Decision checklist before you publish a chart

  1. Can I state the question in one sentence, and does the title answer it with a number?
  2. Is the reference fixed, and named on the axis?
  3. Does every bar start at a meaningful zero? Are outliers marked rather than deleted?
  4. Does palette_report pass, or does every failing pair have a second cue?
  5. Does the chart still work in the deuteranopia render and in greyscale?
  6. Are the data limits on the chart: noise band, frozen telemetry, assumptions (fuel correction) and n?
  7. Is there a source line, alt text and a described-figure paragraph?

What's Next

Charts describe what happened. Chapter 26 asks what will happen next. It builds qualifying and race prediction models on the baselines this chapter just drew (a pole-sitter wins about half the time), checks their calibration with reliability plots, and simulates the rest of the 2026 championship. Every one of those outputs is a distribution, and you now know how to draw one honestly.