Week 4 • Monday

Block 31: Matplotlib: Figures & Axes

Understand the Figure/Axes hierarchy and create basic line plots.

Concepts

Code Examples

Basic line plot

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 5, 6])
ax.set_xlabel('X')
ax.set_ylabel('Y')
plt.show()

Figure and Axes

fig = plt.figure(figsize=(6, 4))
ax = fig.add_subplot(111)
ax.plot([1, 2, 3], [1, 4, 9])
plt.show()

Exercise

Plot daily temperatures for 7 days as a line chart with labeled axes and title. Plot two overlapping lines on the same axes with a legend.

Solution
import matplotlib.pyplot as plt

days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
temps = [22, 24, 21, 25, 23, 26, 24]

fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(days, temps, marker='o', label='Temperature')
ax.set_xlabel('Day')
ax.set_ylabel('Temperature (°C)')
ax.set_title('Weekly Temperatures')
ax.legend()
ax.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig('temps.png', dpi=150)
plt.show()

Practice Problems

Problem 1: Create a figure with 2 subplots (one above the other). Plot different data in each.

Hint: fig, (ax1, ax2) = plt.subplots(2, 1)

Problem 2: Save a plot as PDF. When would PDF be better than PNG?

Hint: plt.savefig('plot.pdf')

Application

Matplotlib is the workhorse of scientific visualization. Every publication-quality plot in Python starts with Figure and Axes.

Case Study

A data scientist explores sales trends. They use ax.plot() for time series, ax.bar() for category comparisons, and ax.scatter() for correlations. All share the same Figure/Axes model.

Visualization

Build an interactive visualization: plot sin(x) and cos(x) from 0 to 2π on the same axes with different colors and a legend. Add grid lines for readability.

Homework

Explain the difference between plt.plot() and fig, ax = plt.subplots(); ax.plot().