Menu
CoddyTech

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:

A diagram: a gray box marked fig, the whole picture, holds a blue box marked ax, the chart. ax.set_title sits above it, ax.set_xlabel below, ax.set_ylabel to its left, ax.plot draws the line inside

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 icon

Challenge

Medium

The starter charts a library's seven branches with plt functions: one dot per branch. Rewrite it in the ax form:

  1. Start with fig, ax = plt.subplots().
  2. Draw the dots, title and both labels with ax methods, same texts.
  3. Delete the old plt lines, keeping plt.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()
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Data and Plots

Practice on your own: Online Python compiler