Matplotlib Basics & Figure Anatomy
π§± Core objects
| Object | What it is |
|---|---|
Figure | The whole window/canvas. Can hold multiple Axes. |
Axes | One individual plot (despite the name, not βaxisβ). Has x-axis, y-axis, title, data. |
Axis | A 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. Useax.set_xlabel()instead once you have more than one plot.
π pyplot vs OO β same thing, different call
| pyplot | OO 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 figureIn Jupyter,
%matplotlib inlinerenders automatically βplt.show()often unnecessary but harmless to include.