Figures and Axes
Part of the Data and Plots section of Coddy's Machine Learning journey. Lesson 24 of 60.
Real code names the chart it draws on. plt.subplots() returns two things: the figure, the whole picture, and the axes, the chart inside it:
fig, ax = catches both. Then everything happens on ax:
years = [2021, 2022, 2023, 2024]
members = [35, 48, 61, 59]
fig, ax = plt.subplots()
ax.plot(years, members)
ax.set_title("Club Members")
ax.set_xlabel("Year")
ax.set_ylabel("Members")
plt.show()Drawing methods keep their names: ax.plot, ax.scatter, ax.legend. Text methods gain set_.
Why bother? Soon one figure holds several charts, and ax says which one you mean. From here on, every chart starts this way.
Challenge
MediumThe starter charts a library's seven branches with plt functions: one dot per branch. Rewrite it in the ax form:
- Start with
fig, ax = plt.subplots(). - Draw the dots, title and both labels with
axmethods, same texts. - Delete the old
pltlines, keepingplt.show().
The chart stays the same; only the code changes. The starter's report says Drawn with fig and ax: no. Yours should read:
Charts drawn: 1
Drawn with fig and ax: yes
Title: Library Branches
X label: Hours open per week
Y label: Loans per week
Lines: 0
Dots: 7
Across (x): [30, 45, 38, 52, 24, 60, 41]
Up (y): [410, 690, 520, 800, 300, 930, 610]Try it yourself
import matplotlib.pyplot as plt
# One value per branch of the city library
hours = [30, 45, 38, 52, 24, 60, 41]
loans = [410, 690, 520, 800, 300, 930, 610]
# Rewrite this chart with fig, ax = plt.subplots() and ax methods
plt.scatter(hours, loans)
plt.title("Library Branches")
plt.xlabel("Hours open per week")
plt.ylabel("Loans per week")
plt.show()
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Data and Plots
2NumPy Arrays
Creating ArraysShape and SizeRanges of NumbersIndexing and SlicingRecap: Temperature Grid5Line and Scatter Plots
Labels and TitlesScatter PlotsSeveral Lines and LegendsColors and MarkersFigures and AxesRecap: Weekly StepsPractice on your own: Online Python compiler