Lesson 10
Working with Figure and Axes Objects
Use plt.subplots to hold the figure and its axes in variables, and learn the set_ methods that replace the plt shortcuts on a real project.
Everything so far has used plt.something, which acts on whichever axes happens to be current. That is comfortable for one chart and fragile for several. The alternative is to keep the objects: ask for the figure and the axes, put them in variables, and say exactly which one you mean. Almost all published Matplotlib code is written this way.
Ask for both objects
plt.subplots() returns a pair: the figure and the axes. Unpack them into two names and you never have to wonder which plot a call will land on.
import matplotlib.pyplot as plt
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
signups = [42, 58, 51, 66, 73, 61, 47]
figure, area = plt.subplots(figsize=(8, 4))
area.plot(days, signups, marker="o")
area.set_title("Signups last week")
area.set_xlabel("day")
area.set_ylabel("people")
area.grid(axis="y", alpha=0.4)
print(type(figure).__name__, "and", type(area).__name__)
plt.show()Output:
Figure and AxesThe names that change
Most of the shortcuts gain a set_ prefix on an axes object. A few keep their names. Learn the pattern once and the whole interface follows.
import matplotlib.pyplot as plt
pairs = [
("plt.title(...)", "area.set_title(...)"),
("plt.xlabel(...)", "area.set_xlabel(...)"),
("plt.ylim(...)", "area.set_ylim(...)"),
("plt.xticks(...)", "area.set_xticks(...)"),
("plt.plot(...)", "area.plot(...)"),
("plt.legend(...)", "area.legend(...)"),
("plt.suptitle(...)", "figure.suptitle(...)"),
]
for shortcut, method in pairs:
print(f"{shortcut:<20} {method}")The translation table:
plt.title(...) area.set_title(...)
plt.xlabel(...) area.set_xlabel(...)
plt.ylim(...) area.set_ylim(...)
plt.xticks(...) area.set_xticks(...)
plt.plot(...) area.plot(...)
plt.legend(...) area.legend(...)
plt.suptitle(...) figure.suptitle(...)A grid of axes
Pass a number of rows and columns and plt.subplots hands back an array of axes instead of one. Index it like any array, or use .flat to walk every panel in reading order.
import matplotlib.pyplot as plt
days = ["Mon", "Tue", "Wed", "Thu", "Fri"]
weekly = {
"Northgate": [12, 18, 14, 21, 25],
"Eastport": [9, 11, 15, 13, 12],
"Westfield": [22, 19, 24, 28, 31],
"Southbank": [5, 8, 7, 11, 14],
}
figure, grid = plt.subplots(2, 2, figsize=(10, 6))
print("shape of the axes array:", grid.shape)
for area, (depot, values) in zip(grid.flat, weekly.items()):
area.plot(days, values, marker="o")
area.set_title(depot)
area.set_ylim(0, 35)
figure.suptitle("Deliveries by depot", fontsize=15)
figure.tight_layout()
plt.show()Output:
shape of the axes array: (2, 2)Giving every panel the same set_ylim matters here. Without it each panel scales itself, and four charts that look alike would be showing four different ranges.
Sharing an axis
sharex=True ties the panels to one x range and hides the repeated tick labels, and sharey=True does the same for the value axis. Sharing y is the honest default when panels are meant to be compared.
import matplotlib.pyplot as plt
days = ["Mon", "Tue", "Wed", "Thu", "Fri"]
north = [12, 18, 14, 21, 25]
west = [22, 19, 24, 28, 31]
figure, (top, bottom) = plt.subplots(2, 1, figsize=(8, 5), sharex=True, sharey=True)
top.plot(days, north, marker="o")
top.set_title("Northgate")
bottom.plot(days, west, marker="s", color="#EC4899")
bottom.set_title("Westfield")
bottom.set_xlabel("day")
print("same y range:", top.get_ylim() == bottom.get_ylim())
figure.tight_layout()
plt.show()Output:
same y range: TrueKey takeaways
-
plt.subplots() returns the figure and the axes together
-
On an axes, most plt shortcuts gain a set_ prefix
-
Rows and columns return an array of axes; .flat walks them in order
-
sharey keeps panels on one scale so they can honestly be compared
-
Next: Bar Charts
-
Previous: Several Plots in One Figure
Loading playground…
Check your understanding
Working with Figure and Axes Objects Quiz
What does plt.subplots() return?
1 / 10