Matplotlib Basics & Figure Anatomy

🧱 Core objects

ObjectWhat it is
FigureThe whole window/canvas. Can hold multiple Axes.
AxesOne individual plot (despite the name, not β€œaxis”). Has x-axis, y-axis, title, data.
AxisA single x or y axis within an Axes β€” ticks, labels, limits.
Figure
 └── Axes (one subplot)
      β”œβ”€β”€ xaxis / yaxis
      β”œβ”€β”€ title, labels
      └── plotted data (lines, points, bars...)

🎯 Object-oriented API (preferred)

import matplotlib.pyplot as plt
 
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 1, 5])
ax.set_title("Title")
ax.set_xlabel("X")
ax.set_ylabel("Y")
plt.show()

🎯 pyplot (implicit) API

import matplotlib.pyplot as plt
 
plt.plot([1, 2, 3], [4, 1, 5])
plt.title("Title")
plt.xlabel("X")
plt.ylabel("Y")
plt.show()

plt.xlabel() acts on the "current" axes β€” gets confusing fast with multiple subplots. Use ax.set_xlabel() instead once you have more than one plot.

πŸ” pyplot vs OO β€” same thing, different call

pyplotOO equivalent
plt.plot(...)ax.plot(...)
plt.title(...)ax.set_title(...)
plt.xlabel(...)ax.set_xlabel(...)
plt.ylabel(...)ax.set_ylabel(...)
plt.xlim(...)ax.set_xlim(...)
plt.legend(...)ax.legend(...)
plt.show()plt.show() (same, always)

πŸ–ΌοΈ Creating a figure explicitly

fig = plt.figure(figsize=(8, 5))          # size in inches
ax = fig.add_subplot(1, 1, 1)                # 1 row, 1 col, 1st subplot
 
fig, ax = plt.subplots(figsize=(8, 5))          # shorthand, same result

πŸ‘οΈ Displaying / closing

plt.show()          # render the figure (blocking in scripts)
plt.close()             # close current figure, free memory
plt.close("all")           # close every open figure
plt.close(fig)                # close a specific figure

In Jupyter, %matplotlib inline renders automatically β€” plt.show() often unnecessary but harmless to include.

πŸ”— Next

Matplotlib Plot Types Β· Matplotlib Subplots & Layouts