Scientific visualization with matplotlib
The matplotlib object-oriented API (Figure, Axes, Artist) for experiment diagnostics and publication-quality figures. Covers perception principles (perceptually uniform color maps, logarithmic scales, small multiples), honest representation of uncertainty across seeds, reproducible scripted vector figures, and algorithm animation.
After this lesson you can
- Build figures with the object-oriented API and control each Artist, including layouts with subplot_mosaic.
- Choose chart type, scale (linear, log, symlog), and colormap suited to message and data.
- Represent variation across seeds with well-defined bands or intervals instead of a single curve.
- Generate reproducible scripted figures with paper-column style and size, exported in vector format.
- Animate an algorithm or simulation using FuncAnimation.
Before you start
Motivation: the figure is the argument
You trained two model variants and want to know which is better. You run each once, draw both validation-loss curves with plt.plot, and the new method ends lower. The conclusion seems obvious, but the figure does not support it: another seed could reverse the ordering, and nothing in the plot warns you. In the uncertainty interactive you will see that with this example’s numbers, one seed per method reverses the conclusion one time in four.
Second scenario. You draw a loss surface with imshow and the jet colormap, and sharp yellow and cyan rings appear around the minimum. They look like ridges, thresholds, perhaps a regime change. None exist: the surface is perfectly smooth, and the colormap creates the rings because its brightness rises and falls even while the data only rise.
Neither mistake is a programming error. They are statistical and perceptual decisions the figure makes for you unless you make them: what is averaged, what the band represents, how a number maps to brightness, which scale reveals structure. This lesson treats visualization as it is in research, a measurement instrument and a paper’s main argument, on two levels:
- The machine. matplotlib is an object hierarchy (Figure, Axes, Axis, Artist) with coordinate transformations. Understanding it lets you control each pixel, write reusable drawing functions, and animate without redrawing everything.
- Judgment. Logarithmic scales and relatives (symlog, logit), perceptually uniform colormaps, uncertainty bands corresponding to defined statistical quantities, small multiples with shared scales, and scripted reproducible paper figures.
Distinguish two uses with different needs. Diagnostic figures are for you while investigating: training curves, activation histograms, gradient norms. They must be quick to make and, above all, not mislead; the reader is you an hour later, when you no longer remember each curve’s seed. Communication figures appear in a paper, report, or presentation: a reader unfamiliar with your code must extract a concrete conclusion in seconds without asking you. Both share honesty rules (scales, bands, color) and differ in finish (size, typography, format). This lesson covers both using code that builds figures explicitly, without hidden state or manual touch-ups.
This lesson’s cells run in your browser with real matplotlib; figures use the Oryon Learn style except when we build our own paper style.
Anatomy of a figure
Everything visible in a matplotlib figure is a Python object, and those objects form a tree. The library has three layers: a backend that draws on a specific medium (pixels with Agg, vectors in PDF or SVG), an artists layer knowing what to draw, and a scripting layer, pyplot, facilitating interactive use.
Three naming confusions are worth resolving upfront. An Axes (with s, even singular) is a panel with its own data coordinate system, colloquially “a plot.” An Axis is one of its two axes, but not the line drawing it (that is a Spine): it contains ticks, their labels, the axis label, and objects deciding tick positions (Locator) and text (Formatter). The grid is not a separate object: each tick has its own gridline.
Transforms: four coordinate systems
To draw a curve in data coordinates , matplotlib chains transformations until pixels. The four systems encountered in practice are:
| System | Object | and | Purpose |
|---|---|---|---|
| Data | ax.transData | depends on xlim, ylim, and scale | curves, points, data annotations |
| Axes | ax.transAxes | Axes bottom-left and top-right corners | panel labels “a)”, text fixed relative to axes |
| Figure | fig.transFigure | figure corners | global titles, elements between panels |
| Display | IdentityTransform() | pixels from bottom left | rarely used manually: the destination |
transData is actually a composition: first nonlinear scaling (for example, on a logarithmic axis), then the affine map taking the limits rectangle to the unit square, and finally transAxes, taking the unit square to the Axes rectangle in pixels. Thus changing ax.set_yscale("log") touches no curve data: only the first link changes. There are also blended transforms, such as ax.get_xaxis_transform(), using data coordinates in and axes coordinates in : axvline uses this to draw a vertical line always spanning the panel bottom to top regardless of ylim.
Ticks, formatting, and drawing order
Two interchangeable Axis objects decide tick positions and text. The Locator chooses positions: MaxNLocator(5) seeks “round” values dividing the axis into at most five intervals, MultipleLocator(0.25) puts a tick every 0.25, and LogLocator puts one per decade and, if requested, minor ticks at times each power of 10. The Formatter converts each position to text: PercentFormatter(1.0) writes 0.25 as 25%, EngFormatter(unit="B") writes 3e9 as 3 GB, FuncFormatter(f) accepts any function. Install them with ax.xaxis.set_major_locator(...) and ax.xaxis.set_major_formatter(...); this is preferable to writing labels manually with set_xticklabels, because a Locator continues working when limits change and fixed labels do not.
Drawing order is determined by zorder: Artists are painted from low to high. By default patches and collections (bands, bars) have 1, lines 2 and text 3, usually the order you want: the band under its curve, text above everything. If a band covers a curve, use zorder rather than changing call order. Put the grid below the data with ax.set_axisbelow(True).
Finally, the backend. The same Artist tree can be drawn with a pixel renderer (Agg, which produces the PNGs on this page), a vector renderer (PDF, SVG, PS), or in an interactive window. Thus the same figure saves in any format without changes: savefig chooses the renderer from the file extension.
pyplot is a stateful facade
pyplot maintains two hidden global variables: the current figure and current Axes (plt.gcf() and plt.gca()). Functions like plt.plot, plt.title and plt.ylim act on them. This is convenient in an exploratory cell but causes errors with multiple panels: the current Axes is the last created or activated, not the last one drawn on with the object-oriented API. This is the same problem as hidden notebook state: the result depends on history not written in the line you read.
The rule in this lesson and throughout the course: use pyplot only to create figures (plt.subplots, plt.subplot_mosaic) and display them; do everything else with Axes methods. Drawing functions receive the Axes as an argument and return the Artists they create:
def dibuja_curvas(ax, x, Y, **kw):
"""Dibuja en ax (nunca en plt.gca()) y devuelve lo creado, para poder modificarlo o comprobarlo."""
lineas = ax.plot(x, Y.T, **kw)
return lineas
This way a function works for a standalone panel, the third panel of a grid, or a test inspecting what was drawn (as you will do in the exercises).
import numpy as np
import matplotlib.pyplot as plt
from collections import Counter
x = np.linspace(0, 10, 101)
fig, ax = plt.subplots(figsize=(6.4, 4.2), dpi=100)
line_a, = ax.plot(x, 0.22 + 0.9 * np.exp(-x / 2.2), label="A")
line_b, = ax.plot(x, 0.34 + 0.78 * np.exp(-x / 3.6), label="B")
banda = ax.fill_between(x, line_a.get_ydata() - 0.04, line_a.get_ydata() + 0.04, alpha=0.2)
ax.set(xlim=(0, 10), ylim=(0, 1.2), xlabel="época", ylabel="pérdida", title="Pérdida de validación")
ax.annotate("mejor época", xy=(7, 0.25), xytext=(4.6, 0.62), arrowprops=dict(arrowstyle="->"))
ax.legend()
# 1. Todo lo que se ve es un Artist dentro de un contenedor
def recorrer(artist):
yield artist
for hijo in artist.get_children():
yield from recorrer(hijo)
tipos = Counter(type(a).__name__ for a in recorrer(fig))
print("Artists en la figura:", sum(tipos.values()))
print("los más frecuentes:", tipos.most_common(5))
print("hijos directos del Axes:", sorted({type(a).__name__ for a in ax.get_children()}))
# 2. Un mismo punto en cuatro sistemas de coordenadas
fig.canvas.draw() # fija la disposición antes de pedir píxeles
p_px = ax.transData.transform((7, 0.25)) # datos -> píxeles (origen abajo a la izquierda)
print(f"\n(7, 0.25) en datos -> píxeles {np.round(p_px, 1)}")
print("en coordenadas de ejes: ", np.round(ax.transAxes.inverted().transform(p_px), 3))
print("en coordenadas de figura:", np.round(fig.transFigure.inverted().transform(p_px), 3))
plt.show()
# 3. La trampa: pyplot dibuja en el Axes «actual», que es el último creado
fig1, ax1 = plt.subplots(figsize=(3, 2))
fig2, ax2 = plt.subplots(figsize=(3, 2))
plt.plot([0, 1], [0, 1]) # ¿en cuál de los dos cae?
print("\nlíneas en ax1:", len(ax1.lines), " líneas en ax2:", len(ax2.lines))
plt.close("all")A figure with two curves, a band, an annotation and a legend has over a hundred Artists, mostly Line2D and Text inside axis ticks. The point falls at in axes coordinates, exactly as expected for and . And the plt.plot line ends up in ax2, the last Axes created, even if you had another one in mind.
Layouts: panel grids without fighting margins
A research figure almost never has a single panel. The tools, from least to most flexible:
plt.subplots(nrows, ncols, sharex=..., sharey=...)returns a regular grid of Axes as a NumPy array. Withsharey=Trueall panels share limits and changing one changes all; withsharey="row", only panels in each row share them.plt.subplot_mosaic(layout)describes the layout with labels: repeat a panel’s name to make it span two cells. It returns a label Axes dictionary, much more readable thanaxs[1, 2].width_ratiosandheight_ratiosdivide the space;fig.subfiguresnests figures inside figures for complex compositions.
The classic problem is margins: labels protrude, titles overlap, color bars steal space. layout="constrained" solves a constraint system to prevent overlap and align panels in the same row; it is preferable to tight_layout, which adjusts margins only once when called, handles legends outside the panel and some color bars poorly, and does not work with subfigures.
Two easily forgotten geometric details. If the panel shows something with geometric meaning (a planar trajectory, image, matrix), units on both axes must have equal length: ax.set_aspect("equal"); otherwise a circle becomes an ellipse and a right angle no longer looks right. If instead all panels must have the same shape despite different data, ax.set_box_aspect(1) fixes the box ratio, not the unit ratio. For groups of panels with their own title or color bar, fig.subfigures(1, 2) divides the figure into independent subfigures, each with its own subplots or subplot_mosaic.
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(0)
mosaico = [["curvas", "curvas", "final"],
["lr", "mapa", "final"]]
fig, axd = plt.subplot_mosaic(mosaico, figsize=(7.5, 4.6), layout="constrained",
width_ratios=[1, 1, 0.8])
t = np.arange(1, 201)
for k, c in enumerate(["C0", "C1"]):
curvas = 0.3 + 0.1 * k + 2 * t[None, :] ** -0.6 * np.exp(0.05 * rng.standard_normal((5, 200)))
axd["curvas"].plot(t, curvas.T, color=c, lw=0.8, alpha=0.5)
axd["final"].scatter(np.full(5, k) + 0.08 * rng.standard_normal(5), curvas[:, -1], color=c)
axd["curvas"].set(xlabel="paso", ylabel="pérdida", title="5 semillas por método")
axd["final"].set(xticks=[0, 1], xticklabels=["A", "B"], title="pérdida final")
lr = np.logspace(-4, -1, 30)
axd["lr"].semilogx(lr, (np.log10(lr) + 2.5) ** 2 + 0.3)
axd["lr"].set(xlabel="tasa de aprendizaje", title="barrido de lr")
im = axd["mapa"].imshow(rng.standard_normal((8, 8)).cumsum(0), cmap="viridis")
fig.colorbar(im, ax=axd["mapa"], shrink=0.8)
axd["mapa"].set_title("activaciones")
print(list(axd)) # un dict: etiqueta -> Axes
plt.show()Scales: what a linear scale hides
A scale is a monotonic function applied to the data before the affine transformation that maps them to the panel. With ax.set_yscale("log"), a point’s height is proportional to , so equal axis distances correspond to equal ratios in the data: 0.01 to 0.1 is as far as 1 to 10. This matters because learning curves span orders of magnitude, and the two most frequent forms of convergence become straight lines on the right scale.
Proof
(1) With and , the graph is the line if and only if ; set . (2) With , the line is equivalent to ; set , .
∎Both appear continually. Gradient descent on a smooth, strongly convex function converges geometrically, with : a straight line on semilog axes. A large model’s loss against steps, parameters, or data closely follows a power law plus an irreducible floor, , the form of neural scaling laws. The floor bends the line, and calculating how much is instructive.
Hence the recipe: to estimate , do not fit a line to against ; estimate or fix and fit . In the cell below, the naive fit gives an exponent three times smaller than the true one (a serious treatment is the subject of power-law fitting).
Two more scales complete the repertoire:
- symlog (
set_yscale("symlog", linthresh=c)) is linear in and logarithmic outside, preserving sign. It suits signed quantities spanning orders of magnitude and crossing zero: parameter updates, reinforcement learning advantages, cumulative returns. The threshold is a choice: below it ratios are indistinguishable. State it in the caption. - logit (
set_yscale("logit")) plots for : it stretches both the region near 0 and near 1. Going from 99% to 99.9% accuracy divides error by 10, and on logit looks as large as going from 50% to 91%. An often clearer alternative is to plot the error rate on a logarithmic scale.
Three warnings about logarithmic scales. First, zero and negative values have no logarithm, and matplotlib gives no error: by default (nonpositive="clip") it replaces them with a tiny positive number far below the panel, which autoscaling ignores. A point with exactly zero loss or a negative metric disappears without warning, and a line through it falls vertically at the bottom edge as if it were a real collapse. Second, when smoothing a noisy curve for a logarithmic plot, smooth its logarithm rather than its values (an average over orders of magnitude is dominated by the largest), and remember that an exponential moving average with factor delays the curve by steps on average (99 for ). Third, when the natural axis has two units (steps and epochs, parameters and FLOPs), ax.secondary_xaxis("top", functions=(f, f_inv)) adds the second axis as a transformation of the first instead of plotting twice.
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(1)
t = np.unique(np.logspace(0, 4, 300).astype(int))
L = 0.4 + 3 * t ** -0.5 * np.exp(0.03 * rng.standard_normal(t.size)) # potencia con suelo 0.4
pend, _ = np.polyfit(np.log10(t), np.log10(L - 0.4), 1)
print(f"pendiente en log-log de L - 0.4: {pend:.3f} (exponente verdadero: -0.5)")
pend_mal, _ = np.polyfit(np.log10(t), np.log10(L), 1)
print(f"sin restar el suelo: {pend_mal:.3f} (no estima nada)")
g = rng.standard_t(1.5, 2000) * 10.0 ** rng.uniform(-3, 1, 2000) # magnitud con signo y colas pesadas
acc = 1 - 0.5 * np.exp(-np.linspace(0, 9, 200)) # precisión que satura en 1
fig, axs = plt.subplots(1, 3, figsize=(9, 3), layout="constrained")
axs[0].loglog(t, L - 0.4, label="L − 0.4")
axs[0].loglog(t, L, label="L", alpha=0.6)
axs[0].legend(); axs[0].set_title("log-log")
bordes = np.concatenate([-np.logspace(3, -3, 40), np.logspace(-3, 3, 40)])
axs[1].hist(g, bins=bordes)
axs[1].set_xscale("symlog", linthresh=1e-3); axs[1].set_title("symlog, linthresh = 0.001")
axs[2].plot(np.arange(200), acc); axs[2].set_yscale("logit"); axs[2].set_title("logit")
plt.show()Color: maps that do not invent structure
A colormap is a function ; a normalization (Normalize, LogNorm, CenteredNorm…) first maps data to . The eye does not perceive RGB components separately: it mainly perceives lightness, ordering it much more reliably than hue. “Lighter” reads as “more” without a legend; “greener than blue” means nothing. Perceived lightness is measured by the coordinate of CIELAB, from 0 (black) to 100 (white). It is calculated by linearizing sRGB, obtaining relative luminance and applying (with a linear segment for very small ). The coefficients tell a story: green weighs ten times as much as blue. The cube root is not arbitrary either: perceived lightness grows approximately as a power of physical luminance, so gray with 18% of white’s luminance appears halfway between black and white (). That is why a linear physical-luminance ramp looks mostly light and why maps are designed in rather than .
jet and rainbow maps violate both conditions. Their goes from 13 in dark blue to 96 in yellow and falls to 25 in the final dark red: the highest values are almost as dark as the lowest. Perceptual speed also varies greatly: around cyan and yellow a small data change produces a large color jump, interpreted as an edge. viridis, designed by Nathaniel Smith and Stéfan van der Walt in 2015 (introduced in matplotlib 1.5 and the default since matplotlib 2.0 in 2017), is monotonic in and approximately uniform in CAM02-UCS; cividis (Nuñez and colleagues, 2018) is also perceived nearly identically with the most common color vision deficiencies, affecting around 8% of men and 0.5% of women of northern European ancestry.
The practical rules that follow:
| Data | Map | Normalization |
|---|---|---|
| ordered quantity without a center (density, loss, time) | sequential: viridis, cividis, magma | Normalize, or LogNorm across orders of magnitude |
| signed or with a meaningful center (correlation, difference, residual, saliency) | diverging: RdBu_r, coolwarm, PuOr | CenteredNorm(0), TwoSlopeNorm(vcenter=0) or vmin=-m, vmax=m |
| unordered categories (method, seed, class) | qualitative: color cycle, Okabe-Ito, tab10 | none; at most eight categories |
| cyclic (angle, phase, time of day) | cyclic: twilight | Normalize over one exact period (0 to , 0 to 24 h) |
An often-forgotten detail: the default limits of imshow are the data minimum and maximum. For a correlation matrix ranging from to , this puts white at , not , coloring a small positive correlation like a negative one. The interactive shows this with the uncentered difference field.
Uniformity depends on the color space used to measure it. In CIELAB, color difference between consecutive steps of jet’s 256 ranges from 0 to 4.5: in some regions, such as pure blue around , color does not change at all; in others, around cyan, every step is a visible jump. Viridis varies by a factor of only 2.2 (0.5 to 1.15), because it was optimized in CAM02-UCS, a space more faithful to perception than CIELAB; even a linear sRGB grayscale ramp varies by a factor of 1.9, because sRGB is not perceptually uniform. The lesson is not that a perfect map exists, but that rainbows have blind and jumping regions absent from reasonable alternatives.
Three more tools. If data span several orders of magnitude (a density with tails, a matrix’s singular values), LogNorm does for color what set_yscale("log") does for position. If a few discrete levels matter, BoundaryNorm or contour lines communicate better than a continuous gradient because the eye compares distant colors poorly. For lines, color is a label, not a quantity: use a qualitative cycle, at most about eight categories, and the same color for the same method in every figure of a paper, so readers learn the mapping once.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colormaps
from matplotlib.colors import CenteredNorm
def srgb_a_lineal(c):
return np.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4)
def luminosidad(rgb):
"""L* de CIELAB (0 = negro, 100 = blanco) de colores sRGB en [0, 1], forma (..., 3)."""
Y = srgb_a_lineal(rgb) @ np.array([0.2126, 0.7152, 0.0722]) # luminancia relativa
f = np.where(Y > (6 / 29) ** 3, np.cbrt(Y), Y / (3 * (6 / 29) ** 2) + 4 / 29)
return 116 * f - 16
v = np.linspace(0, 1, 256)
print(f"{'mapa':8s} {'L*(0)':>6s} {'L* máx':>7s} {'en v =':>7s} {'L*(1)':>6s} monótona tramo plano")
for nombre in ["jet", "turbo", "viridis", "cividis", "gray", "RdBu_r"]:
L = luminosidad(colormaps[nombre](v)[:, :3])
pend = np.gradient(L, v) # dL*/dv
monotona = np.all(pend >= -1) or np.all(pend <= 1) # tolera ruido de cuantización
plano = np.mean(np.abs(pend) < 15) # fracción del mapa con menos de 1.5 L* por 10 %
print(f"{nombre:8s} {L[0]:6.1f} {L.max():7.1f} {v[L.argmax()]:7.2f} {L[-1]:6.1f} {str(monotona):8s} {plano:6.0%}")
x, y = np.meshgrid(np.linspace(-2, 2, 300), np.linspace(-1, 1, 150))
g = lambda cx, cy, a, b: np.exp(-(x - cx) ** 2 / a - (y - cy) ** 2 / b)
perdida = 1.25 - 0.9 * g(0.75, 0.15, 0.55, 0.3) - 0.6 * g(-0.95, -0.3, 0.3, 0.25) + 0.07 * x ** 2
dif = 0.9 * g(0.55, 0.1, 0.7, 0.5) - 0.38 * g(-1.15, -0.2, 0.25, 0.3)
fig, axs = plt.subplots(2, 2, figsize=(8, 4.4), layout="constrained", sharex=True, sharey=True)
for ax, (z, cmap, norm, titulo) in zip(axs.flat, [
(perdida, "jet", None, "pérdida, jet: anillos que no existen"),
(perdida, "viridis", None, "pérdida, viridis"),
(dif, "RdBu_r", None, "diferencia, sin centrar"),
(dif, "RdBu_r", CenteredNorm(0), "diferencia, CenteredNorm(0)")]):
im = ax.imshow(z, cmap=cmap, norm=norm, extent=(-2, 2, -1, 1), origin="lower")
ax.set_title(titulo, fontsize=10)
fig.colorbar(im, ax=ax, shrink=0.85)
plt.show()The table confirms what you saw. jet rises from to a maximum of 96 at (yellow), then falls to 25: the highest data value is almost as dark as the lowest. Moreover, over 12% of its range (mostly between cyan and green), lightness barely changes, making different values look alike. turbo, Google’s improved rainbow published in 2019, is smoother but peaks in the middle: it does not encode order either. viridis and cividis are monotonic with no flat regions; RdBu_r peaks at the center, exactly what a diverging map should do.
Uncertainty: one seed is not a result
Training is a random experiment: initialization, data order, dropout and GPU nondeterminism depend on the seed (explored in depth in multi-seed evaluation). The final loss of a run is a random variable with mean and standard deviation , and a training curve is a realization of a process . A single curve is a sample of size 1. With seeds , several quantities can be plotted as bands, and they answer different questions.
This is uncertainty visualization: represent variability with the band that answers the reader’s question, and state which it is in the caption. “Mean 1 SE over 3 seeds” and “mean 1 SD over 3 seeds” differ in width by a factor of ; without a caption neither is interpretable. With , SE is not a 95% interval: because follows a distribution with 2 degrees of freedom, it covers the true mean only 58% of the time.
The probability of a reversed comparison has a closed form. If A and B’s seeds are independent and normal, the difference of means is normal with mean and variance , so
which equals for , for , for , and for . Going from one to four seeds per method reduces the chance of a wrong conclusion from 25% to 8.5%. It is the difference between a result and a biased coin.
Three more traps common in papers:
- Choosing the best seed. If are independent normal variables with mean and SD , the maximum has expectation , where is the expected maximum of standard normals (an order statistic): , , . Publishing the best of 5 seeds inflates the result by over one standard deviation without a new method.
- Reading pointwise bands as global. A 95% interval calculated separately at each epoch contains that epoch’s true value with probability 0.95, but the probability that the entire true curve lies inside is lower. Claims about the whole curve require simultaneous bands (for example, bootstrapping whole curves; see nonparametric bootstrap).
- Comparing without pairing. If seed fixes initialization and data order in both methods, differences often have much lower variance than either method separately. The honest plot then shows the difference with its interval, rather than two overlapping bands.
The last point deserves a calculation. If results from the two methods with the same seed have correlation , the difference’s variance is . With the interactive’s numbers and (realistic when the seed fixes validation data and initialization), the difference’s standard deviation falls from to , and the probability that one pair gives the wrong conclusion falls from 25% to 10%. Pairing is free and equivalent to more than tripling the number of seeds. But this is visible only when plotting the per-seed difference: two independent bands, one per method, hide the correlation.
With few seeds, the best representation is often all curves, thin and translucent, or the full distribution of final values: individual points, a violin (ax.violinplot), or the empirical cumulative distribution function (ax.ecdf, see empirical cumulative distribution function), showing every run without choosing smoothing. When the horizontal axis is discrete (one point per method, model size or hyperparameter value), the band equivalent is an error bar: ax.errorbar(x, media, yerr=semianchura, fmt="o", capsize=3). yerr accepts an array of shape containing downward and upward distances, as needed for asymmetric intervals (percentiles, bootstrap). As with bands, the caption must state what the bar represents and how many seeds were used.
If you do not want to assume normality for the mean’s interval, the bootstrap provides a direct alternative: repeatedly resample the seeds with replacement, calculate each resample’s mean, and take the 2.5th and 97.5th percentiles of those means. With very few seeds bootstrap cannot work miracles (with only 10 distinct resamples exist), but with 10 or more it robustly yields intervals for any statistic, including medians or differences between methods. When curves are noisy step by step, decide whether the band describes variation across seeds or minibatch noise within each: smooth each curve first (with the same window for all), then calculate the across-seed band, or its width mixes both sources.
Experimental data work well in long format, one row per (method, seed, epoch), as in tidy data. Each band is then a split-apply-combine: group by method and epoch and aggregate.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
epocas = np.arange(101)
def entrenar(metodo, semilla):
"""Curva simulada de una ejecución: media del método más un efecto propio de la semilla."""
r = np.random.default_rng([semilla, int(metodo == "B")])
mu, sigma, tau = (0.30, 0.05, 18) if metodo == "A" else (0.34, 0.03, 12)
efecto = sigma * r.standard_normal()
ruido = 0.01 * r.standard_normal(epocas.size)
return mu + (1.6 - mu) * np.exp(-epocas / tau) + efecto * (1 - np.exp(-epocas / 25)) + ruido
# formato largo: una fila por (método, semilla, época)
df = pd.concat([pd.DataFrame({"metodo": m, "semilla": s, "epoca": epocas, "perdida": entrenar(m, s)})
for m in "AB" for s in range(10)], ignore_index=True)
print(df.shape)
por_grupo = df.groupby(["metodo", "epoca"])["perdida"] # split
res = por_grupo.agg(media="mean", dt="std", n="count") # apply + combine
cuantiles = por_grupo.quantile([0.1, 0.9]).unstack() # vectorizado, sin lambdas
res["p10"], res["p90"] = cuantiles[0.1], cuantiles[0.9]
res = res.reset_index()
res["ee"] = res["dt"] / np.sqrt(res["n"])
T975 = {3: 4.303, 5: 2.776, 10: 2.262, 30: 2.045} # scipy.stats.t.ppf(0.975, n - 1)
res["ic"] = res["n"].map(T975) * res["ee"] # semianchura del IC del 95 %
print(res[res.epoca == 100].round(4).to_string(index=False))
fig, axs = plt.subplots(1, 3, figsize=(10, 3.2), layout="constrained")
for (m, g), c in zip(res.groupby("metodo"), ["C0", "C1"]):
for ax, (lo, hi, nombre) in zip(axs[:2], [(g.media - g.dt, g.media + g.dt, "media ± DT"),
(g.media - g.ic, g.media + g.ic, "media e IC 95 % (t)")]):
ax.plot(g.epoca, g.media, color=c, label=m)
ax.fill_between(g.epoca, lo, hi, color=c, alpha=0.2, lw=0)
ax.set(ylim=(0.2, 0.9), title=f"{nombre}, n = 10", xlabel="época")
axs[2].ecdf(df[(df.metodo == m) & (df.epoca == 100)]["perdida"], color=c, label=m)
axs[0].legend(); axs[2].set(title="ECDF de la pérdida final", xlabel="pérdida en la época 100")
plt.show()
fA = df.query("metodo == 'A' and epoca == 100").perdida.to_numpy()
fB = df.query("metodo == 'B' and epoca == 100").perdida.to_numpy()
dif = fB.mean() - fA.mean()
# contraste de permutación desde cero: ¿cuántas reasignaciones de etiquetas dan una diferencia igual de grande?
todos = np.concatenate([fA, fB])
perm = np.random.default_rng(0).permuted(np.tile(todos, (20000, 1)), axis=1)
difs = perm[:, 10:].mean(axis=1) - perm[:, :10].mean(axis=1)
print(f"\nB − A en la época 100: {dif:.3f} (permutación: p = {(np.abs(difs) >= abs(dif)).mean():.3f})")
print(f"fracción de pares (semilla de A, semilla de B) en que gana B: {(fB[:, None] < fA[None, :]).mean():.2f}")With 10 seeds, the mean difference is and the permutation test gives , right at the usual 5% threshold (and since the methods’ variances differ, Welch’s test, scipy.stats.ttest_ind(fB, fA, equal_var=False), would be more appropriate and gives ): even ten runs do not make a 0.04 difference with these variances clearly conclusive. In slightly more than one in five individual pairs, B comes out ahead. The methods’ SD bands overlap widely at the end; confidence interval bands much less so. Both figures are correct: they answer different questions.
Small multiples: comparing many conditions at a glance
First, the principle. Cleveland and McGill (1984) experimentally measured how accurately we judge quantities encoded in different ways, finding an ordering that still guides chart design: most accurate is position on a common scale; then position on aligned but different scales; then lengths, angles and areas; least accurate is color intensity. Two direct consequences follow. Quantities readers must compare precisely belong in the same panel or side-by-side panels with the same scale. Color distinguishes and provides an overall impression, rather than conveying precise values (hence a heatmap needs a color bar and, when values matter, written numbers).
When comparing many conditions (learning rates, model sizes, datasets), putting them all in one panel produces a tangle of curves with a twelve-entry legend. The alternative, popularized by Edward Tufte, repeats the same small chart for each condition.
The first rule is broken most often, because plt.subplots does not share scales by default: each panel autoscales to its data, making curves of very different heights look alike. With sharey=True, height means the same in every panel; if ranges differ too much for sharing to make sense, a shared logarithmic scale often helps. Otherwise the caption must explicitly state that scales differ.
The same rule applies to color. A grid of heatmaps (attention by head, activations by layer, loss by hyperparameter pair) where each imshow autoscales is the color equivalent of not sharing the axis: yellow in one panel and the next means different numbers. Calculate one normalization for all, for example norm = Normalize(vmin, vmax) using the global minimum and maximum, pass it to each imshow, and add a single color bar for the group with fig.colorbar(im, ax=axs).
In practice, small multiples come directly from a long DataFrame: each condition value is a groupby group, each group a panel. Sort groups by the condition’s numeric value (not its string representation, or “1e-3” comes before “3e-4”) and plot with a function receiving the Axes, like the first coding exercise.
import numpy as np
import matplotlib.pyplot as plt
t = np.arange(1, 1001)
lrs = [1e-4, 3e-4, 1e-3, 3e-3]
def curva(lr, metodo):
suelo = {"Adam": 0.25, "SGD": 0.32}[metodo]
vel = lr * {"Adam": 30, "SGD": 12}[metodo]
inestable = 0.4 * (lr / 3e-3) ** 3 if metodo == "Adam" else 0.0
return suelo + inestable + 2.0 / (1 + vel * t) ** 0.7
def paneles(compartir):
fig, axs = plt.subplots(1, 4, figsize=(9, 2.6), layout="constrained", sharex=True, sharey=compartir)
for ax, lr in zip(axs, lrs): # orden con sentido: lr creciente
for metodo, c in [("Adam", "C0"), ("SGD", "C1")]:
y = curva(lr, metodo)
ax.plot(t, y, color=c)
ax.annotate(metodo, (t[-1], y[-1]), xytext=(-2, 4), textcoords="offset points",
ha="right", color=c, fontsize=9) # etiqueta directa
ax.set_title(f"lr = {lr:g}", fontsize=10)
ax.set_yscale("log")
for ax in axs:
ax.label_outer() # etiquetas solo en el borde de la rejilla
axs[0].set_ylabel("pérdida")
fig.supxlabel("paso", fontsize=10)
return fig, axs
for compartir, titulo in [(False, "Cada panel se autoescala: las alturas no se comparan"),
(True, "sharey=True: la misma altura es la misma pérdida en todos")]:
fig, axs = paneles(compartir)
fig.suptitle(titulo, fontsize=11)
print(f"sharey={compartir!s:5s} límites en y:", ", ".join(f"({a:.2f}, {b:.2f})" for a, b in (ax.get_ylim() for ax in axs)))
plt.show()In the first row, the panel looks as good as because its axis starts at 0.97 instead of 0.41. In the second, it is immediately clear that the smaller rate does not converge within 1000 steps and Adam with the larger rate plateaus higher.
Figures for papers
A paper figure has a physical size fixed by the template (one column or page width), text size similar to the body, and a vector format that stays sharp at any magnification. It must be regenerable from data with one command, because review will require changes.
The key points:
- Size. matplotlib measures in inches: . An 8.5 cm column is 3.35 inches; NeurIPS has a 5.5-inch text width and ICML two 3.25-inch columns. Create the figure at that size. If a 6.4-inch figure is reduced to 3.35 by LaTeX, everything scales by and 10 pt labels become an unreadable 5.2 pt.
- Fonts. Use 7–9 pt for a column figure and a single family. Embed TrueType fonts with
pdf.fonttype = 42: matplotlib defaults to Type 3 fonts, which some submission systems reject and cannot be edited. - Format. PDF or SVG for line plots, saved as vectors. A scatter plot with points produces a huge, slow PDF: draw that layer with
rasterized=True(only that Artist is rasterized; the rest remains vector) and setsavefig.dpito 300 or more. - Style in code. Use an
rcParamsdictionary or.mplstylefile versioned with the project, applied withplt.style.context([...])instead of changing global values. Starting from"default"avoids inheriting the environment’s style (Oryon Learn’s here; yourmatplotlibrcon your machine). - Determinism. SVG contains a creation date and random internal identifiers;
metadata={"Date": None}andsvg.hashsaltfix them (for PDF,metadata={"CreationDate": None}). The file is then byte-identical across runs and version control shows only real changes. This is a particular case of reproducibility levels. - Resolution, only for rasterized parts. A vector figure has no resolution. Rasterized parts (images, layers with
rasterized=True, or the whole figure when exporting PNG) have pixels: width in inches times dots per inch. A column figure at 300 dpi is about 1000 pixels wide. Screens need much less; 300 is the usual print minimum. - Beware
bbox_inches="tight". It crops or expands the canvas to fit everything, changing the carefully chosen final size. For paper figures uselayout="constrained"and save without cropping; reserve"tight"for diagnostics. - Typography consistent with the text.
mathtext.fontset = "cm"imitates LaTeX formula typography without installing LaTeX;text.usetex = Trueuses actual LaTeX at the cost of speed and an external dependency.
Before submitting a figure, check: is it readable at final size, printed in grayscale and by someone with color blindness? Does each axis have a quantity and units? Does each band say what it is and how many seeds? Do compared panels share scales? Can it be regenerated from data with one command?
Lab: the course figure template
This cell is the style module you will use throughout the course: size constants, a paper style with the Okabe-Ito palette (designed to remain distinguishable with color vision deficiencies), functions plotting multi-seed curves with bands and a matrix with a centered diverging map, and deterministic export checked by regenerating the figure twice.
import hashlib
import io
import re
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import CenteredNorm
from cycler import cycler
CM = 1 / 2.54 # matplotlib mide en pulgadas
COLUMNA = 8.5 * CM # una columna de un artículo a dos columnas
PAGINA = 17.8 * CM # ancho de texto completo
OKABE_ITO = ["#0072B2", "#E69F00", "#009E73", "#D55E00", "#CC79A7", "#56B4E9", "#F0E442", "#000000"]
ESTILO = {
"figure.figsize": (COLUMNA, 0.62 * COLUMNA), "figure.dpi": 150, "savefig.dpi": 300,
"font.family": "DejaVu Sans", "font.size": 8, "axes.titlesize": 8, "axes.labelsize": 8,
"xtick.labelsize": 7, "ytick.labelsize": 7, "legend.fontsize": 7, "legend.frameon": False,
"axes.linewidth": 0.6, "lines.linewidth": 1.2, "xtick.major.width": 0.6, "ytick.major.width": 0.6,
"xtick.major.size": 3, "ytick.major.size": 3, "axes.spines.top": False, "axes.spines.right": False,
"axes.prop_cycle": cycler(color=OKABE_ITO), "image.cmap": "viridis",
"pdf.fonttype": 42, "ps.fonttype": 42, # TrueType incrustadas, no Type 3
"svg.fonttype": "path", "svg.hashsalt": "atlas-m00-l11", # identificadores internos deterministas
}
def estilo():
"""Valores de fábrica de matplotlib (no los del entorno) más ESTILO."""
return plt.style.context(["default", ESTILO])
def curvas_con_banda(ax, x, Y, etiqueta, color, banda="ee"):
"""Y: (semillas, puntos). Media y banda de ±1 EE o de percentiles 10-90, con etiqueta directa."""
media = Y.mean(axis=0)
if banda == "ee":
ee = Y.std(axis=0, ddof=1) / np.sqrt(len(Y))
lo, hi = media - ee, media + ee
else:
lo, hi = np.percentile(Y, [10, 90], axis=0)
linea, = ax.plot(x, media, color=color)
zona = ax.fill_between(x, lo, hi, color=color, alpha=0.25, lw=0)
ax.annotate(etiqueta, (x[-1], media[-1]), xytext=(3, 0), textcoords="offset points",
va="center", color=color)
return linea, zona
def matriz_divergente(ax, M, titulo):
im = ax.imshow(M, cmap="RdBu_r", norm=CenteredNorm(0)) # blanco = 0, simétrico
ax.set(title=titulo, xticks=[], yticks=[])
return ax.figure.colorbar(im, ax=ax, shrink=0.8)
def figura_resultados():
rng = np.random.default_rng(0)
paso = np.arange(1, 301)
with estilo():
fig, (a, b) = plt.subplots(1, 2, figsize=(PAGINA, 0.32 * PAGINA), layout="constrained",
width_ratios=[1.6, 1])
for k, nombre in enumerate(["A", "B"]):
Y = 0.3 + 0.05 * k + 2 * paso ** -0.5 * np.exp(0.08 * rng.standard_normal((5, paso.size)))
curvas_con_banda(a, paso, Y, nombre, f"C{k}")
a.set(xscale="log", yscale="log", xlabel="paso", ylabel="pérdida", title="media ± 1 EE, 5 semillas")
C = np.corrcoef(rng.standard_normal((6, 40)) + 0.6 * rng.standard_normal(40))
matriz_divergente(b, C - np.eye(6), "correlaciones (diagonal a 0)")
return fig
def exportar_svg(fig):
buf = io.BytesIO()
with estilo(): # svg.hashsalt y los colores «CN» se leen al guardar
fig.savefig(buf, format="svg", metadata={"Date": None})
return buf.getvalue()
svg1 = exportar_svg(figura_resultados())
svg2 = exportar_svg(figura_resultados())
ancho, alto = (float(v) for v in re.search(rb'width="([\d.]+)pt" height="([\d.]+)pt"', svg1).groups())
print(f"tamaño: {ancho:.1f} x {alto:.1f} pt = {ancho / 72:.2f} x {alto / 72:.2f} pulgadas")
print("sha256 de las dos exportaciones:", hashlib.sha256(svg1).hexdigest()[:16], hashlib.sha256(svg2).hexdigest()[:16])
print("idénticas byte a byte:", svg1 == svg2)
plt.close("all")
fig = figura_resultados()
plt.show()In a real project, everything before figura_resultados lives in a module (estilo_curso.py), each paper figure is a function reading saved experiment data, and a make_figures.py script regenerates them all. The figure on screen has a white background and the Okabe-Ito palette because that is how it will appear in the PDF, regardless of this page’s theme.
Animations with FuncAnimation
An animation maps a frame number to a figure state. FuncAnimation(fig, actualizar, frames=...) calls actualizar(i) for each frame and rasterizes the figure. The object model holds the key to efficiency: create Artists once and change only their data each frame with set_data, set_offsets, set_array or set_text. Clearing the Axes with ax.clear() and redrawing everything recreates ticks, text and grid each frame.
With blit=True and an interactive backend, matplotlib saves the background and redraws only the Artists returned by actualizar each frame, greatly speeding on-screen playback. Saving to a file rasterizes every frame in full. PillowWriter produces GIF without external dependencies; FFMpegWriter produces much more compact MP4 if ffmpeg is installed; in Jupyter, anim.to_jshtml() embeds a player. Always keep a reference to the animation object: otherwise garbage collection destroys it and the animation stops.
Lab: animating a simulation
The N-body simulation from the broadcasting lesson, now animated. First we measure frame cost for both strategies, then save a GIF.
import base64
import time
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation, PillowWriter
EPS2 = 0.05 ** 2 # gravedad suavizada
def aceleraciones(pos, masa):
d = pos[None, :, :] - pos[:, None, :] # (N, N, 2)
r2 = (d * d).sum(axis=-1) + EPS2
w = masa[None, :] / (r2 * np.sqrt(r2))
np.fill_diagonal(w, 0.0)
return (w[:, :, None] * d).sum(axis=1)
rng = np.random.default_rng(5)
N, dt = 150, 0.01
pos = rng.standard_normal((N, 2))
vel = 0.3 * rng.standard_normal((N, 2))
vel -= vel.mean(axis=0)
masa = np.full(N, 1.0 / N)
acc = aceleraciones(pos, masa)
def paso(k=2):
global pos, vel, acc
for _ in range(k): # leapfrog: impulso, deriva, impulso
vel += 0.5 * dt * acc
pos += dt * vel
acc = aceleraciones(pos, masa)
vel += 0.5 * dt * acc
def preparar(ax):
ax.set(xlim=(-3, 3), ylim=(-3, 3), aspect="equal", xticks=[], yticks=[])
puntos = ax.scatter(pos[:, 0], pos[:, 1], s=6, c=np.hypot(*vel.T), cmap="viridis", vmin=0, vmax=1)
texto = ax.text(0.03, 0.94, "", transform=ax.transAxes, fontsize=8)
return puntos, texto
fig, ax = plt.subplots(figsize=(3.2, 3.2), dpi=80, layout="constrained")
puntos, texto = preparar(ax)
def actualizar(i):
paso()
puntos.set_offsets(pos) # solo cambian los datos de los Artists
puntos.set_array(np.hypot(*vel.T))
texto.set_text(f"t = {2 * (i + 1) * dt:.2f}")
return puntos, texto
def redibujar(i): # la alternativa ingenua: rehacer el Axes
paso()
ax.clear()
p, tx = preparar(ax)
tx.set_text(f"t = {2 * (i + 1) * dt:.2f}")
def coste(f, reps=8, dibujar=True):
t0 = time.perf_counter()
for i in range(reps):
f(i)
if dibujar:
fig.canvas.draw() # rasteriza el fotograma, como al guardar
return (time.perf_counter() - t0) / reps
c_sim = coste(lambda i: paso(), dibujar=False)
c_act = coste(actualizar) - c_sim
c_red = coste(redibujar) - c_sim
print(f"por fotograma: simulación {1e3 * c_sim:.1f} ms; dibujo actualizando datos {1e3 * c_act:.1f} ms;"
f" dibujo rehaciendo el Axes {1e3 * c_red:.1f} ms ({c_red / c_act:.1f} veces más)")
ax.clear()
puntos, texto = preparar(ax)
anim = FuncAnimation(fig, actualizar, frames=24, interval=60, blit=True)
t0 = time.perf_counter()
anim.save("/tmp/ncuerpos.gif", writer=PillowWriter(fps=12))
print(f"GIF de 24 fotogramas guardado en {time.perf_counter() - t0:.1f} s")
plt.close(fig)
class GIF:
"""Muestra un GIF en la salida de la celda (como IPython.display.Image)."""
def __init__(self, ruta):
self.datos = open(ruta, "rb").read()
def _repr_html_(self):
b64 = base64.b64encode(self.datos).decode()
return f'<img alt="Animación de N cuerpos" width="256" src="data:image/gif;base64,{b64}">'
GIF("/tmp/ncuerpos.gif")Exact measurements depend on the machine, but the ordering remains: updating data is cheaper than rebuilding the Axes (in the browser it takes roughly half the drawing time per frame), because rebuilding recreates Artists and recalculates text layout. Here the difference is moderate because the panel has no ticks or labels and much of the cost is figure rasterization, common to both strategies; with ticks, grid, legend and several panels, rebuilding creates tens or hundreds of Artists per frame and the ratio grows. On screen, blit=True also lets data updates redraw only changed Artists. For an animation with thousands of frames, or a figure updating during training, this difference separates fluid from unusable.
Animation is not always the best way to show change. Readers cannot precisely compare frame 3 with frame 40 because they cannot see both at once, and a printed paper does not move. Animations excel at conveying qualitative dynamics (an orbit, an optimization trajectory, cluster formation) and in presentations; for quantitative comparisons, a row of small multiples at four or five chosen moments on the same scales is often better. Good work commonly provides both: animation as supplementary material and the grid of moments in the text.
Common mistakes
Exercises
More than one answer may be correct.
For the next exercise, this code creates a figure with two panels:
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.plot(x, perdida_train)
ax2.plot(x, perdida_val)
ax1.set_xlabel("época")
plt.title("Entrenamiento")
plt.ylim(0, 1)
plot_runs(df, x, y, hue, ax). df is a long-format DataFrame (for example columns opt, semilla, epoca, loss, one row per run and epoch, not necessarily sorted). For each value of the hue column, in alphabetical order, draw on `ax` (never with plt) the mean of y against x, with x sorted and the group value as label, and a fill_between band from the 10th to 90th percentile of y at each x, in the same color as the line. Return a dictionary {grupo: (linea, banda)} containing the created Artists.import pandas as pd
def plot_runs(df, x, y, hue, ax):
"""Media y banda de percentiles 10-90 de y frente a x, una por cada valor de hue."""
artistas = {}
# tu código: agrupa por hue; dentro de cada grupo, agrega y por x (media, cuantiles 0.1 y 0.9),
# dibuja la línea y la banda del mismo color y guarda (linea, banda) en artistas[grupo]
return artistasfigura_objetivo(df, tareas). df has columns tarea, metodo, paso and perdida (unsorted). Return a figure with one row of panels, one per task in the order of the `tareas` list, 17.8 cm wide and 2.4 inches high, a shared y axis across all panels, logarithmic x and y scales, the task name as title, one curve per method sorted by step and labeled with the method, the label ‘paso’ (step) on x in every panel, ‘pérdida’ (loss) on y only in the first, and a legend only in the first.import matplotlib.pyplot as plt
def figura_objetivo(df, tareas):
"""Una fila de paneles, uno por tarea en el orden dado, con las curvas de cada método."""
fig, axs = plt.subplots(1, len(tareas))
for ax, tarea in zip(axs, tareas):
d = df[df.tarea == tarea]
for metodo, g in d.groupby("metodo"):
ax.plot(g["paso"], g["perdida"])
# tu código: tamaño, eje y compartido, escalas, títulos, etiquetas y leyenda
return figSummary
- Everything visible is an Artist in a Figure › Axes › Axis › Tick tree. Use
pyplotonly to create and show; draw withaxmethods in functions receiving the Axes and returning Artists. Data, axes, figure and pixels are four coordinate systems linked by transforms. - A power law is a straight line on log-log axes, with its exponent as slope; geometric convergence is a straight line on semilog axes. An irreducible floor bends the line: local slope is . Use symlog for signed quantities and logit (or log error) for probabilities near 0 or 1.
- Colormaps should have monotonic lightness and uniform perceptual speed: viridis or cividis for ordered data, a diverging map with centered normalization for data with a center. jet invents edges.
- One seed is not a result. SD, SE, CI and percentiles answer different questions; always state which you plot and how many seeds. Choosing the best of seeds biases results upward.
- Use small multiples with shared scales, meaningful order and direct labels.
- Paper figures: final size in inches, fonts of 7–9 pt, style fixed in code, vector format and deterministic export. For animation, create Artists once and update only their data.