5 min read min read
Figure and Axes Objects
Learn the building blocks of matplotlib charts
Figure and Axes Objects
What are Figure and Axes?
- Figure = The whole image (like a canvas)
- Axes = One chart inside the figure
Think of it like:
- Figure = A piece of paper
- Axes = A drawing on that paper
Simple Way (plt)
code.py
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [1, 4, 9])
plt.show()This works but gives less control.
Better Way (fig, ax)
code.py
import matplotlib.pyplot as plt
# Create figure and axes
fig, ax = plt.subplots()
# Plot on the axes
ax.plot([1, 2, 3], [1, 4, 9])
plt.show()This gives you more control!
Why Use fig, ax?
code.py
fig, ax = plt.subplots()
# Add title to axes
ax.set_title('My Chart')
# Add labels
ax.set_xlabel('X Axis')
ax.set_ylabel('Y Axis')
# Plot data
ax.plot([1, 2, 3], [1, 4, 9])
plt.show()Set Figure Size
code.py
# figsize = (width, height) in inches
fig, ax = plt.subplots(figsize=(10, 6))
ax.plot([1, 2, 3], [1, 4, 9])
plt.show()Multiple Charts in One Figure
code.py
# 1 row, 2 columns = 2 charts side by side
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))
# First chart
ax1.plot([1, 2, 3], [1, 4, 9])
ax1.set_title('Chart 1')
# Second chart
ax2.bar(['A', 'B', 'C'], [10, 20, 15])
ax2.set_title('Chart 2')
plt.show()Grid of Charts
code.py
# 2 rows, 2 columns = 4 charts
fig, axes = plt.subplots(2, 2, figsize=(10, 8))
# Access each chart
axes[0, 0].plot([1, 2, 3], [1, 4, 9])
axes[0, 1].bar(['A', 'B'], [5, 10])
axes[1, 0].scatter([1, 2, 3], [3, 2, 1])
axes[1, 1].plot([1, 2, 3], [9, 4, 1])
plt.tight_layout() # Prevent overlap
plt.show()Key Methods
| plt style | ax style |
|---|---|
| plt.title() | ax.set_title() |
| plt.xlabel() | ax.set_xlabel() |
| plt.ylabel() | ax.set_ylabel() |
| plt.xlim() | ax.set_xlim() |
| plt.ylim() | ax.set_ylim() |
Recommended Pattern
code.py
import matplotlib.pyplot as plt
# Always start with this
fig, ax = plt.subplots(figsize=(8, 6))
# Create your chart
ax.plot(x, y)
# Customize
ax.set_title('Title')
ax.set_xlabel('X')
ax.set_ylabel('Y')
# Show or save
plt.show()Key Points
- Figure = whole image canvas
- Axes = individual chart
- fig, ax = plt.subplots() is the recommended way
- Use figsize=(width, height) to set size
- Multiple charts: plt.subplots(rows, cols)
- plt.tight_layout() prevents overlapping
What's Next?
Learn to create line plots for showing trends over time.