Skip to main content

Matplotlib (Part 2): Customizing plots (labels, titles, colors)

You can render truthful data with default styles and still fail communication: unreadable subtitles, clipped legends, categorical colors masquerading as quantitative ramps. Part 1 drew the skeleton; here you add purposeful annotation.


πŸ“š Prerequisites​

  • Completed Matplotlib Part 1 (explicit Axes usage).

🎯 What you'll master​

  • Title,subtitle, ticks, legends with readable defaults.
  • Use colormaps intentionally (cmap) and annotate notable points.

Labels, grids, legends​

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(8, 4))
ax.plot([1, 2, 3], [3, 2, 4], label="experiment A")
ax.plot([1, 2, 3], [2, 3, 2.5], label="experiment B", linestyle="--")
ax.set_title("Latency replay")
ax.set_xlabel("Trial")
ax.set_ylabel("Latency (ms)")
ax.grid(True, linestyle=":", linewidth=0.6)
ax.legend(frameon=False, loc="upper left")
plt.tight_layout()
plt.show()

fig.subplots_adjust remains available when tight_layout cannot reconcile wide colorbars.


Color maps for scatter density​

Avoid rainbow maps for continuous science plots; perceptually uniform ramps such as viridis reduce misreadings:

import numpy as np

rng = np.random.default_rng(0)
x = rng.normal(size=200)
y = rng.normal(size=200)

fig, ax = plt.subplots()
sc = ax.scatter(x, y, c=y, cmap="viridis", s=35, alpha=0.8)
fig.colorbar(sc, ax=ax, label="Derived metric")
plt.show()

Annotating spikes​

ax.annotate(
"spike",
xy=(2, 4),
xytext=(2.2, 3.6),
arrowprops=dict(arrowstyle="->", color="gray"),
)

Reserve annotations for anomalies you intend to narrate verbally.


πŸ’‘ Key takeaways​

  • Every axis needs units or domain contextβ€”even internal dashboards decay without them.
  • Treat color as data encoding, not ornament.

➑️ Next steps​

Arrange multiples in Matplotlib (Part 3): Subplots and figures.