The Object-Oriented API
The Object-Oriented API
Every plot belongs to a Figure containing Axes — grab them explicitly:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(x, y, label="throughput", color="#1f77b4", linestyle="--")
ax.scatter(x2, y2, marker="o", s=40)
ax.set_xlabel("requests/s"); ax.set_ylabel("p99 ms")
ax.set_title("Latency under load")
ax.legend(); ax.grid(True, alpha=0.3)
fig.tight_layout()
The stateful shorthand (plt.plot) targets the "current" axes — convenient in a REPL, error-prone when building multiple panels because a stray call can draw into the wrong subplot. The OO form scales from one line to dashboards: ax is a handle you can pass into helper functions that add layers without global state.
Panels, Ticks, and Saving
Panels, Ticks, and Saving
fig, axes = plt.subplots(2, 2, figsize=(10, 7), sharex=True)
for a, (title, frame) in zip(axes.flat, frames):
a.hist(frame["value"], bins=30)
a.set_title(title)
ax.set_xticks([0, 5, 10])
ax.set_xticklabels(["low", "mid", "high"], rotation=30)
fig.savefig("report.png", dpi=150, bbox_inches="tight")
bbox_inches='tight' crops the margin whitespace that otherwise floats labels off-canvas; dpi controls print resolution. For dates on the x-axis, pass datetime objects directly and call fig.autofmt_xdate(). Headless servers should select a non-GUI backend before importing pyplot: matplotlib.use("Agg") or MPLBACKEND=Agg — plt.show() then becomes a no-op and savefig does the work.
Seaborn Layering and Pitfalls
Seaborn Layering and Pitfalls
Seaborn is a layer on matplotlib, not a replacement — it returns the same Figure/Axes objects:
import seaborn as sns
sns.set_theme(style="darkgrid", context="talk") # styling + scaled fonts
g = sns.relplot(data=df, x="hour", y="orders",
hue="region", kind="line", col="year")
sns.regplot(data=df, x="temp", y="sales", ax=ax) # drop into an existing Axes
Common problems:
savefigaftershowmay save a cleared figure — save first- Open figures leak memory in loops: call
plt.close(fig) - Categorical axis order follows first appearance — set
hue_order/orderto control it - Global style: call
sns.set_theme()once at entry, not per plot
Interview angle: describe a layered workflow — data → seaborn for statistical geometry → matplotlib ax for annotation and tweaks — and the CI backend choice.
Quiz
1. Why prefer fig, ax = plt.subplots() over bare plt.plot() in scripts?
2. What does bbox_inches="tight" in savefig change?
3. Why call plt.close(fig) after drawing many figures in a loop?
Flashcards
Question
fig vs ax
Click to reveal answer
Answer
Figure = the canvas/window holding one or more Axes; Axes = one plot with its own data, ticks, labels.
Question
plt.subplots
Click to reveal answer
Answer
Creates figure + axes in one call; returns arrays of Axes when rows/cols > 1.
Question
Headless backend
Click to reveal answer
Answer
matplotlib.use("Agg") or MPLBACKEND=Agg — render to files with no display server.
Question
seaborn.set_theme
Click to reveal answer
Answer
Sets grid/style/context globally; seaborn plots still return matplotlib Axes for tweaks.
Revision Notes
Key Takeaways
- 1. Own the fig/ax objects; pyplot is convenience glue, not the architecture
- 2. savefig with dpi and bbox_inches before any show; close figures in loops
- 3. Seaborn adds statistical layers onto matplotlib objects — annotate with ax afterward
Interview Tips
- • Mention the Agg backend when asked how you would generate charts in CI or a container
- • Explain the layered model (seaborn geometry + matplotlib annotation) rather than treating libraries as rivals
Cheat Sheet
fig,ax=plt.subplots(); ax.plot/scatter/hist + set_xlabel/legend; savefig(dpi, bbox_inches="tight") before show; MPLBACKEND=Agg headless; sns.set_theme.