Foundations to Frontier
Tests
C. Programming, Tools and HPC › C1 Python for Science

Matplotlib, Seaborn and Plotly

Plots are how engineers check, debug and communicate results. Matplotlib is the foundational, fully controllable plotting library (Figure → Axes → Artists, object-oriented API, saving at a chosen DPI); Seaborn adds statistical plots on top of it from tidy DataFrames; Plotly makes interactive, zoomable web figures. This topic covers the figure anatomy and the explicit (fig, ax) style, subplots and shared axes, log scales, annotations and shaded regions, saving publication-quality vector and raster output, and choosing colours honestly (perceptually uniform colormaps, accessibility). In the exercises you build and programmatically test a two-panel telemetry figure, then measure the perceptual lightness of colormaps to see why jet misleads.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

A picture checks your numbers

A table of 10 000 voltages tells you almost nothing; a plot shows instantly that the voltage sagged at minute five. Good plots are how engineers find problems (a sensor glitch, a diverging simulation) and how they convince others. A good plot is honest: its axes are labelled with units, it doesn’t invent patterns, and anyone (including colour-blind readers) can read it.

Does your colormap tell the truth?
perceived lightness L* along the map (0–100)
❌ lightness reverses direction 3 times
The field is a smooth ramp with one small bump near the middle. Our eyes read lightness, not hue, as "more". With viridis or gray the ramp looks smooth and the bump is visible as a local brightening; with jet, bright cyan and yellow bands appear where nothing happens in the data, and the bump can vanish into a band. Use perceptually uniform maps (viridis, cividis, magma) for sequential data, diverging maps (coolwarm, RdBu) only when there is a meaningful centre, and test in grayscale and for colour-blind viewers (cividis).
Why engineers care

Quick-look plots are the first line of defence in flight operations and testing; trajectory, thermal and structural results are judged from plots in design reviews; and a misleading colormap or a missing unit can lead a review to the wrong conclusion. Interactive plots (Plotly) let operators zoom into anomalies in long telemetry streams.

📝 Quick check (Level 0)
0/3 answered
  1. 1. An honest plot always has…
  2. 2. Which library makes interactive, zoomable web plots?
  3. 3. The rainbow 'jet' colormap can…

Level 1: Beginner

★★☆☆☆ Basic⏱ 25 minSecondary-school mathematics: arithmetic and elementary algebra.

Figure anatomy and the explicit style

A Figure contains one or more Axes (plotting areas), each with lines, patches, text and so on (Artists). Prefer the explicit object-oriented API:

import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(6, 4), constrained_layout=True)
ax.plot(t, v, label="bus voltage")
ax.axhline(27.5, ls="--", color="tab:red", label="limit")
ax.set(xlabel="time [s]", ylabel="voltage [V]", title="EPS bus voltage")
ax.legend(); fig.savefig("eps.pdf")          # vector for papers; .png with dpi=300 for slides

plt.subplots(2, 1, sharex=True) stacks panels; ax.set_yscale("log"), ax.axvspan(...), ax.annotate(...), ax.errorbar(...) and ax.hist(...) cover most engineering needs.

Seaborn and Plotly

Seaborn works on tidy DataFrames: sns.lineplot(df, x="time", y="value", hue="subsystem"), sns.histplot, sns.boxplot, sns.heatmap, with confidence bands and grouping by column. Plotly (plotly.express.line(df, x=..., y=..., color=...)) produces interactive HTML with zoom, hover and toggles: great for exploring long telemetry, less so for print.

📝 Quick check (Level 1)
0/3 answered
  1. 1. A 6 × 4 inch figure saved at 100 dpi is…
  2. 2. Best format for a figure in a printed paper:
  3. 3. plt.subplots(2, 1, sharex=True) gives…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 35 minUndergraduate students and practising engineers.

Making figures that work

  • Units in labels (voltage [V]), readable font sizes at the final print size, and a legend only when there are several series.
  • Scales: log axes for quantities spanning decades (errors, PSDs, counts); symlog for data crossing zero.
  • Context: limit lines, shaded fault windows, annotations at events.
  • Small multiples (a grid of similar panels) beat one overloaded panel.
  • Reproducibility: generate figures from scripts, never edit them by hand; set rcParams or a style file once per project.

Colour

Lightness carries “magnitude” for the eye. Sequential data need a map whose lightness increases monotonically and evenly (viridis, cividis, magma, gray). Diverging data (signed deviations) need a map with a neutral centre (coolwarm, RdBu). Categorical data need distinct hues (tab10). Avoid jet and hsv for continuous data; check for colour-vision deficiency (cividis was designed for it) and grayscale printing.

🐍 Exercise 1: a tested two-panel telemetry figure
Build a figure with a voltage time series (limit line, shaded below-limit window, legend, labelled axes) above a log-scale histogram. Then inspect it programmatically (axes, lines, legend text, scales, bars) and check the PNG pixel size at two DPIs — plots can be unit-tested too.
📝 Quick check (Level 2)
0/3 answered
  1. 1. For signed temperature anomalies (±), choose…
  2. 2. For counts spanning 1 to 10⁶, use…
  3. 3. Which colormap was designed to be readable with colour-vision deficiency?

Level 3: Advanced

★★★★☆ Advanced⏱ 30 minGraduate level, with full derivations and proofs.

Perceptual uniformity, quantitatively

Convert each colour of a map to CIELAB, a space designed so that Euclidean distances roughly match perceived differences. The lightness is

L⋆=116 f(Y)−16,f(y)={y1/3y>(6/29)3y/(3(6/29)2)+4/29otherwiseL^\star = 116\,f(Y) - 16,\quad f(y) = \begin{cases}y^{1/3} & y\gt(6/29)^3\\ y/(3(6/29)^2) + 4/29 & \text{otherwise}\end{cases}

with Y the relative luminance of the linearized sRGB colour. A good sequential map has L⋆L^\star monotone in the data value with nearly constant steps, so equal data steps look equal. Jet’s L⋆L^\star rises to a peak near cyan/yellow, then falls, so the eye sees bright bands (false features) and reads a mid-range value as “highest”.

The rendering pipeline

plt.plot creates Line2D artists; on savefig a backend renders them. Agg rasterizes to pixels (PNG); PDF/SVG backends emit vector paths. The DPI only matters for raster output and text/marker sizing. Headless servers and CI use Agg (matplotlib.use("Agg")), which is also what lets us test figures in this browser.

📝 Quick check (Level 3)
0/3 answered
  1. 1. L* of pure white and pure black are…
  2. 2. Why does jet create false boundaries?
  3. 3. Which backend renders without a display?

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

Figures and colour, measured

Exercise 1. The figure is verified without looking at it: 2 axes, 2 lines on top, the legend entries “bus voltage”, “limit 27.5 V” and “below limit”, a log-scale histogram with 40 bars, and a PNG of 600 × 400 px at 100 dpi and 1200 × 800 px at 200 dpi. Tests like these catch regressions in automated report generation.

Exercise 2: lightness along colormaps (256 samples):

map L* range monotone reversals step unevenness
viridis 76 yes 0 0.06
cividis 77 yes 0 0.09
gray 100 yes 0 0.13
jet 83 no 3 1.19
hsv 64 no 5 1.39
coolwarm 50 no 1 1.09

Jet’s and hsv’s lightness wanders up and down. Coolwarm’s single reversal is intentional: it’s a diverging map, dark-light-dark around the centre.

🐍 Exercise 2 (research): how honest is your colormap?
Convert colormap samples to CIELAB lightness L* (sRGB linearization, luminance, the CIE f function), then for several matplotlib colormaps measure the L* range, monotonicity, number of direction reversals and unevenness of the steps.

Visualization in AI, robotics and aerospace

  • Quick-look telemetry dashboards and anomaly review plots in mission operations.
  • Training curves, confusion matrices and attention maps for ML (consistent, honest colour).
  • Trajectory, thermal and CFD fields rendered with perceptually uniform maps.
  • Automated report generation in CI with tested figures.

References

  1. J. D. Hunter (2007). “Matplotlib: a 2D graphics environment.” Computing in Science & Engineering, 9(3).
  2. N. Smith, S. van der Walt (2015). “A better default colormap for Matplotlib.” SciPy conference (viridis).
  3. J. R. Nuñez, C. R. Anderton, R. S. Renslow (2018). “Optimizing colormaps with consideration for color vision deficiency.” PLOS ONE, 13(7) (cividis).
  4. M. Waskom (2021). “seaborn: statistical data visualization.” Journal of Open Source Software, 6(60).
  5. D. Borland, R. M. Taylor II (2007). “Rainbow color map (still) considered harmful.” IEEE Computer Graphics and Applications, 27(2).
  6. E. R. Tufte (2001). The Visual Display of Quantitative Information, 2nd ed. Graphics Press.