0
0
Matplotlibdata~5 mins

Figure and Axes mental model in Matplotlib

Choose your learning style9 modes available
Introduction

We use the Figure and Axes model to organize and control plots clearly. It helps us put one or many charts in a single window.

When you want to create a single plot in a window.
When you want to put multiple plots side by side or in a grid.
When you want to customize the size or layout of your plots.
When you want to add titles or labels to the whole window or individual plots.
When you want to save your plots as images with specific sizes.
Syntax
Matplotlib
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(width, height))

fig is the whole window or figure that holds one or more plots.

ax is the actual plot area where data is drawn.

Examples
Create one plot and draw a simple line chart.
Matplotlib
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 5, 6])
Create a 2x2 grid of plots and draw lines on two of them.
Matplotlib
fig, axs = plt.subplots(2, 2)
axs[0, 0].plot([1, 2], [3, 4])
axs[1, 1].plot([5, 6], [7, 8])
Create a wider plot and draw a bar chart.
Matplotlib
fig, ax = plt.subplots(figsize=(8, 4))
ax.bar(['A', 'B'], [10, 20])
Sample Program

This code creates one window (figure) with two plots (axes) side by side. The first plot shows a line chart, and the second shows a scatter chart. We add titles to each plot and a main title for the whole window.

Matplotlib
import matplotlib.pyplot as plt

# Create a figure with 2 plots side by side
fig, axs = plt.subplots(1, 2, figsize=(10, 4))

# First plot: line chart
axs[0].plot([1, 2, 3], [1, 4, 9])
axs[0].set_title('Line Chart')

# Second plot: scatter chart
axs[1].scatter([1, 2, 3], [9, 4, 1])
axs[1].set_title('Scatter Chart')

# Add a main title for the whole figure
fig.suptitle('Figure with Two Axes')

# Show the plot window
plt.show()
OutputSuccess
Important Notes

Think of Figure as a picture frame and Axes as the canvas inside where you paint your data.

You can have many Axes inside one Figure to compare different charts easily.

Use figsize to control the size of the whole Figure window.

Summary

The Figure is the whole window or image that holds your plots.

The Axes is the area where the actual data is drawn.

You can create multiple Axes inside one Figure to show many plots together.