Frontend Labs
⋯

55. Plotting just enough: matplotlib

import matplotlib
matplotlib.use("Agg")                       # no window: render to files (servers, CI)
import matplotlib.pyplot as plt
import numpy as np

rng = np.random.default_rng(0)
steps = np.arange(1, 501)
train = 3.0 * steps ** -0.3 + rng.normal(0, 0.03, 500)
val = 3.1 * steps ** -0.28 + rng.normal(0, 0.03, 500)

fig, axes = plt.subplots(1, 2, figsize=(10, 3.5), layout="constrained")
axes[0].plot(steps, train, label="train")
axes[0].plot(steps, val, label="validation")
axes[0].set(xlabel="step", ylabel="loss", title="Learning curve", yscale="log")
axes[0].legend()
axes[1].hist(rng.lognormal(3, 0.6, 2000), bins=50)
axes[1].set(xlabel="latency (ms)", ylabel="requests", title="Latency distribution")
fig.savefig("curves.png", dpi=150)
print("wrote curves.png")

Use the object-oriented API (fig, ax = plt.subplots(), then ax.plot) rather than global plt.plot calls; it scales to multi-panel figures and avoids state bugs. Three plots you will make constantly: learning curves (train vs validation loss: is it learning, is it overfitting?), histograms (is this distribution what I think it is?), and confusion matrices (which classes does the model mix up?). seaborn and plotly add statistical and interactive plots on top.


Generated from real-life-python-guide.md · 8 Oct 2026 16:36