MATPLOTLIB:Figures, axes, and the plotting workflow
Mastering figures, axes, and the plotting workflow concepts and implementation.
The hook
A chart is two objects. The figure is the page. The axes is the panel on that page where the data is drawn. Titles, ticks, and lines belong to the axes. Saving and size belong to the figure.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [1, 4, 9])
ax.set_title("Squares")
fig.savefig("squares.png", dpi=120, bbox_inches="tight")
plt.show()
In a notebook or in the data analysis lab, the figure appears under the cell. savefig writes a PNG when you want a file. plt.show() opens a window in a local script and is harmless in the lab.
Install Matplotlib with pip install matplotlib. The lab already includes it.
Why not only plt.plot
plt.plot(...) works. It draws on whatever axes is "current". That is fine for one panel. The moment you have two panels, or you want to hand the axes to a function, the implicit current axes becomes a source of charts landing in the wrong place. fig, ax = plt.subplots() names both objects. This course uses that form every time.
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(6, 4))
print(type(fig).__name__)
print(type(ax).__name__)
Output:
Figure
Axes
figsize is width and height in inches. (6, 4) is a good default for a single panel.
The order that stays readable
- Create
figandax. - Draw the data (
plot,scatter,bar,hist). - Set the title and axis labels.
- Add a legend only if more than one series is drawn.
- Call
fig.tight_layout()or save withbbox_inches="tight"so labels are not clipped.
What to notice
- One figure can hold many axes. One axes is one panel.
- Methods that style the panel start with
set_:set_title,set_xlabel,set_ylabel. - Leave
plt.show()at the end of a script. In the lab, the figure is captured after the cell finishes, including figures you did not explicitly show.
Try this
Create a figure of size (5, 3), plot [0, 1, 2] against [0, 1, 4], and set the title to "First panel".
Next: line charts and scatter plots, and how to tell which one the data is asking for.