Q&A
What is matplotlib?
Overview
Matplotlib (2003, John Hunter) sits beneath the entire Python visualization ecosystem. Seaborn, pandas plotting, and many other libraries call Matplotlib under the hood. Its strength is completeness: if a plot type or style exists, Matplotlib can produce it. Its learning curve is higher than newer alternatives, but understanding it unlocks everything built on top of it.
graph TD
A[matplotlib] --> B["pyplot: quick, stateful plots"]
A --> C["OO API: Figure + Axes - reusable, precise"]
A --> D["Backends: screen, PNG, PDF, SVG, interactive"]
A --> E["Seaborn / pandas plotting built on top"]
style A fill:#1e1b4b,color:#fff
The Two APIs
pyplot (quick and stateful)
plt.xxx() calls operate on the "current figure/axes" implicitly - fast for exploration:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2 * np.pi, 100)
plt.figure(figsize=(8, 4))
plt.plot(x, np.sin(x), label="sin(x)", color="#6366f1")
plt.plot(x, np.cos(x), label="cos(x)", color="#f97316")
plt.title("Trig Functions")
plt.xlabel("x"); plt.ylabel("y")
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.savefig("trig.png", dpi=150)
plt.show()
Object-Oriented API (recommended for real work)
Create Figure and Axes objects explicitly for clearer, reusable code:
fig, ax = plt.subplots(figsize=(8, 4)) # fig = canvas, ax = the plot area
ax.plot(x, np.sin(x), label="sin(x)")
ax.set_title("Sine Wave")
ax.set_xlabel("x"); ax.set_ylabel("y")
ax.legend(); ax.grid(True)
fig.tight_layout()
fig.savefig("sine.png")
The pattern fig, ax = plt.subplots() gives you handles to both and avoids "which axes am I touching?" ambiguity.
Common Plot Types
# Bar chart
categories = ["A", "B", "C"]
values = [10, 25, 15]
ax.bar(categories, values, color="#6366f1")
# Scatter plot
ax.scatter(x_data, y_data, c=colors, alpha=0.7)
# Histogram
ax.hist(data, bins=30, edgecolor="white")
# Heatmap / imshow
ax.imshow(matrix, cmap="viridis"); fig.colorbar(ax.images[0])
# Subplots (multiple panels)
fig, axes = plt.subplots(2, 3, figsize=(12, 8)) # 2 rows × 3 cols
axes[0, 0].plot(x, y)
axes[1, 2].hist(data)
Customization
Almost everything is configurable: fonts, colors, tick labels, spines, line styles, markers, colormaps:
ax.set_xlim(0, 10); ax.set_ylim(-1, 1)
ax.set_xticks([0, 5, 10]); ax.set_xticklabels(["zero", "half", "full"])
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
Saving Figures
fig.savefig("output.png", dpi=150, bbox_inches="tight") # PNG
fig.savefig("output.pdf") # vector PDF
fig.savefig("output.svg") # scalable SVG
Integration
- pandas -
df.plot()calls Matplotlib. - seaborn - statistical charts with prettier defaults, built on Matplotlib.
- NumPy - arrays are Matplotlib's native input.
- Jupyter -
%matplotlib inlineor%matplotlib widgetfor interactive notebooks.
Why This Matters in Interviews
Data-science interviews use Matplotlib to check visualization fundamentals. Key points: the two APIs (pyplot vs object-oriented, and why OO is preferred); fig, ax = plt.subplots() as the standard idiom; common chart types (line, bar, scatter, histogram, imshow/heatmap); saving to different formats; and the relationship to Seaborn/pandas (wrappers on top). Explaining when to use plt vs ax. methods shows API literacy.
Common Pitfalls
- Mixing
plt.xxx()calls with OOax.xxx()calls confusingly in the same script. plt.show()afterplt.savefig()produces a blank file - save before showing (or close).- Calling
plt.clf()/plt.close()at the wrong time and clearing a figure mid-work. - Not calling
fig.tight_layout()and getting labels clipped. - Displaying in Jupyter without
%matplotlib inlineor an appropriate backend.
References
- Matplotlib docs: https://matplotlib.org/stable/
- Matplotlib tutorials: https://matplotlib.org/stable/tutorials/index.html