Indexing Subplots in Matplotlib
Learn how to access and manage individual Axes objects inside a subplot grid. Understand single Axes objects, one-dimensional arrays, two-dimensional arrays and subplot indexing techniques.
1. Learning Objectives
After completing this lesson, you will be able to:
- Understand how Matplotlib returns Axes objects.
- Access individual subplots using indexes.
- Understand one-dimensional and two-dimensional Axes arrays.
- Use row and column indexes to select subplots.
- Understand the
squeezeparameter. - Use
squeeze=Falsefor consistent indexing. - Use
ax.flatto iterate over multiple subplots. - Handle subplot indexing errors.
2. Introduction to Subplot Indexing
When we create multiple subplots using
plt.subplots(), Matplotlib returns Axes objects that
represent individual plotting areas.
We use indexing to access a particular Axes object and customize its chart. The indexing method depends on the number of rows and columns in the subplot grid.
Why Is Indexing Important?
Suppose we create four charts in a 2 × 2 grid. We may want to add a line chart in the first position, a bar chart in the second position and other chart types in the remaining positions. Indexing helps us select each plotting area independently.
A 2 × 2 subplot grid showing the row and column indexes of each Axes object.
3. Indexing a Single Subplot
When we create only one subplot, Matplotlib returns a single Axes object instead of an array of Axes objects.
Example
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 1)
x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 30, 25]
ax.plot(x, y)
ax.set_title("Single Subplot")
ax.set_xlabel("X Values")
ax.set_ylabel("Y Values")
plt.show()
Expected Output
One figure containing a single line chart.
Axes object:
ax
The chart can be customized directly using ax methods.
ax.plot(). Do not use ax[0] because
ax is not an array in this case.
4. Indexing a One-Dimensional Axes Array
When we create multiple subplots in one row or one column, Matplotlib normally returns a one-dimensional array of Axes objects.
Example: One Row and Three Columns
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 3, figsize=(12, 4))
ax[0].plot([1, 2, 3], [10, 20, 30])
ax[0].set_title("First Plot")
ax[1].plot([1, 2, 3], [20, 15, 25])
ax[1].set_title("Second Plot")
ax[2].plot([1, 2, 3], [5, 15, 10])
ax[2].set_title("Third Plot")
plt.tight_layout()
plt.show()
Expected Output
Three subplots arranged horizontally.
ax[0] = First Plot
ax[1] = Second Plot
ax[2] = Third Plot
A one-dimensional Axes array containing three subplot objects.
Example: Three Rows and One Column
import matplotlib.pyplot as plt
fig, ax = plt.subplots(3, 1, figsize=(7, 8))
ax[0].plot([1, 2, 3], [10, 20, 30])
ax[0].set_title("First Plot")
ax[1].plot([1, 2, 3], [15, 25, 35])
ax[1].set_title("Second Plot")
ax[2].plot([1, 2, 3], [5, 10, 15])
ax[2].set_title("Third Plot")
plt.tight_layout()
plt.show()
Expected Output
Three subplots arranged vertically.
ax[0] = Top subplot
ax[1] = Middle subplot
ax[2] = Bottom subplot
5. Indexing a Two-Dimensional Axes Array
When both rows and columns contain more than one subplot, Matplotlib returns a two-dimensional array of Axes objects.
We access an individual subplot using two indexes:
ax[row, column].
Example: 2 × 2 Subplot Grid
import matplotlib.pyplot as plt
fig, ax = plt.subplots(2, 2, figsize=(10, 7))
ax[0, 0].plot([1, 2, 3], [10, 20, 30])
ax[0, 0].set_title("Top Left")
ax[0, 1].plot([1, 2, 3], [30, 20, 10])
ax[0, 1].set_title("Top Right")
ax[1, 0].bar([1, 2, 3], [10, 20, 30])
ax[1, 0].set_title("Bottom Left")
ax[1, 1].scatter([1, 2, 3], [10, 20, 30])
ax[1, 1].set_title("Bottom Right")
plt.tight_layout()
plt.show()
Expected Output
Four charts arranged in a 2 × 2 grid.
ax[0, 0] = Top Left
ax[0, 1] = Top Right
ax[1, 0] = Bottom Left
ax[1, 1] = Bottom Right
6. Understanding Row and Column Indexes
The following table explains how indexes work in a 3 × 3 subplot grid.
Index positions for all nine Axes objects in a 3 × 3 subplot grid.
| Index | Position |
|---|---|
ax[0, 0] |
First row, first column. |
ax[0, 1] |
First row, second column. |
ax[0, 2] |
First row, third column. |
ax[1, 0] |
Second row, first column. |
ax[1, 1] |
Second row, second column. |
ax[1, 2] |
Second row, third column. |
ax[2, 0] |
Third row, first column. |
ax[2, 1] |
Third row, second column. |
ax[2, 2] |
Third row, third column. |
7. Understanding the squeeze Parameter
The squeeze parameter controls the shape of the Axes
object or array returned by plt.subplots().
By default, squeeze=True. Matplotlib removes
unnecessary dimensions from the returned Axes array.
Default squeeze=True
import matplotlib.pyplot as plt
fig, ax = plt.subplots(
2,
2,
squeeze=True
)
print(type(ax))
print(ax.shape)
plt.show()
Expected Output
Type: numpy.ndarray
Shape: (2, 2)
The Axes objects are stored in a two-dimensional array.
Single Subplot with Default Squeeze
fig, ax = plt.subplots(
1,
1,
squeeze=True
)
print(type(ax))
Expected Output
ax is a single matplotlib.axes.Axes object.
It is not a NumPy array.
One Row with Multiple Columns
fig, ax = plt.subplots(
1,
3,
squeeze=True
)
print(ax.shape)
Expected Output
(3,)
The returned Axes array is one-dimensional.
8. Using squeeze=False
When we set squeeze=False, Matplotlib always returns
a two-dimensional array of Axes objects, even when only one row
or one column is created.
This is useful when we want to use the same row-column indexing approach for different subplot layouts.
Example: Single Subplot
import matplotlib.pyplot as plt
fig, ax = plt.subplots(
1,
1,
squeeze=False
)
ax[0, 0].plot([1, 2, 3], [10, 20, 30])
ax[0, 0].set_title("Single Plot")
print(ax.shape)
plt.show()
Expected Output
Shape: (1, 1)
The Axes object is accessed using ax[0, 0].
Example: One Row and Three Columns
import matplotlib.pyplot as plt
fig, ax = plt.subplots(
1,
3,
squeeze=False
)
ax[0, 0].set_title("First Plot")
ax[0, 1].set_title("Second Plot")
ax[0, 2].set_title("Third Plot")
print(ax.shape)
plt.show()
Expected Output
Shape: (1, 3)
ax[0, 0] = First Plot
ax[0, 1] = Second Plot
ax[0, 2] = Third Plot
Example: Three Rows and One Column
import matplotlib.pyplot as plt
fig, ax = plt.subplots(
3,
1,
squeeze=False
)
ax[0, 0].set_title("First Plot")
ax[1, 0].set_title("Second Plot")
ax[2, 0].set_title("Third Plot")
print(ax.shape)
plt.show()
Expected Output
Shape: (3, 1)
ax[0, 0] = First Plot
ax[1, 0] = Second Plot
ax[2, 0] = Third Plot
When Should You Use squeeze=False?
Use squeeze=False when your code needs consistent
two-dimensional indexing, especially when the number of rows
or columns may change dynamically.
9. Using ax.flat to Access All Subplots
The flat attribute allows us to iterate over all Axes
objects in a multidimensional NumPy array. It provides a convenient
way to access every subplot without manually writing row and column
indexes.
Example
import matplotlib.pyplot as plt
fig, ax = plt.subplots(2, 2, figsize=(9, 6))
titles = [
"First Plot",
"Second Plot",
"Third Plot",
"Fourth Plot"
]
for axis, title in zip(ax.flat, titles):
axis.set_title(title)
axis.plot([1, 2, 3], [10, 20, 30])
plt.tight_layout()
plt.show()
Expected Output
Four line charts are created in a 2 × 2 grid.
First Plot
Second Plot
Third Plot
Fourth Plot
The loop accesses each Axes object using ax.flat.
ax.flat is useful when you want
to apply common formatting or operations to all subplots.
10. Iterating Through Rows and Columns
For a two-dimensional Axes array, we can use nested loops to access each subplot by its row and column position.
Example
import matplotlib.pyplot as plt
fig, ax = plt.subplots(2, 3, figsize=(12, 7))
for row in range(2):
for col in range(3):
ax[row, col].plot([1, 2, 3], [10, 20, 30])
ax[row, col].set_title(
f"Row {row}, Column {col}"
)
plt.tight_layout()
plt.show()
Expected Output
A figure containing six subplots.
Row 0, Column 0
Row 0, Column 1
Row 0, Column 2
Row 1, Column 0
Row 1, Column 1
Row 1, Column 2
11. Common Indexing Errors
1. Using Array Indexing on a Single Axes Object
fig, ax = plt.subplots(1, 1)
ax[0].plot([1, 2, 3], [10, 20, 30])
Problem: The returned value is a single Axes object, not an array.
Correct approach:
ax.plot([1, 2, 3], [10, 20, 30])
2. Using Two Indexes on a One-Dimensional Array
fig, ax = plt.subplots(1, 3)
ax[0, 1].plot([1, 2, 3], [10, 20, 30])
Problem: A 1 × 3 layout normally returns a one-dimensional array.
Correct approach:
ax[1].plot([1, 2, 3], [10, 20, 30])
Alternatively, use squeeze=False if you need
two-dimensional indexing.
3. Accessing an Index That Does Not Exist
fig, ax = plt.subplots(2, 2)
ax[2, 0].plot([1, 2, 3], [10, 20, 30])
Problem: The valid row indexes are 0 and 1. Row index 2 does not exist in this grid.
Correct approach:
ax[1, 0].plot([1, 2, 3], [10, 20, 30])
12. Practical Example: Sales Dashboard Using Indexing
Let's create a small sales dashboard with four charts. We will use two-dimensional indexing to access each plotting area.
Complete Python Program
import matplotlib.pyplot as plt
months = ["Jan", "Feb", "Mar", "Apr"]
sales = [100, 150, 130, 180]
profit = [30, 50, 40, 65]
customers = [50, 70, 65, 90]
orders = [40, 60, 55, 80]
fig, ax = plt.subplots(2, 2, figsize=(11, 8))
# Sales chart
ax[0, 0].bar(months, sales, color="skyblue")
ax[0, 0].set_title("Monthly Sales")
ax[0, 0].set_ylabel("Sales")
# Profit chart
ax[0, 1].plot(months, profit, marker="o", color="green")
ax[0, 1].set_title("Monthly Profit")
ax[0, 1].set_ylabel("Profit")
# Customer chart
ax[1, 0].scatter(months, customers, color="red")
ax[1, 0].set_title("Customers")
ax[1, 0].set_ylabel("Customer Count")
# Orders chart
ax[1, 1].bar(months, orders, color="orange")
ax[1, 1].set_title("Monthly Orders")
ax[1, 1].set_ylabel("Orders")
fig.suptitle("Sales Performance Dashboard")
plt.tight_layout()
plt.show()
Expected Output
Sales Performance Dashboard
Top-left:
Monthly Sales - Bar Chart
Top-right:
Monthly Profit - Line Chart
Bottom-left:
Customers - Scatter Plot
Bottom-right:
Monthly Orders - Bar Chart
All four charts appear inside one figure.
13. Best Practices for Subplot Indexing
- Use direct Axes methods when working with a single subplot.
- Use one-dimensional indexing for a one-row or one-column layout.
- Use row-column indexing for a two-dimensional subplot grid.
- Use
squeeze=Falsewhen consistent 2D indexing is required. - Use
ax.flatto loop through all Axes objects. - Use nested loops when row and column positions are important.
- Check array dimensions before accessing an index.
- Use
plt.tight_layout()to improve subplot spacing when needed.
14. Practice Questions
- What is subplot indexing in Matplotlib?
- What does
plt.subplots()return? - How do you access the second subplot in a 1 × 3 layout?
- How do you access the bottom-right subplot in a 2 × 2 grid?
- What is the difference between a single Axes object and an Axes array?
- What is the default value of the
squeezeparameter? - What happens when
squeeze=Falseis used? - What is the purpose of
ax.flat? - How can you iterate through a two-dimensional Axes array?
- Why should you check array dimensions before accessing a subplot?
Summary
Subplot indexing allows us to access individual Axes objects inside
a Matplotlib figure. The indexing method depends on the number of
rows and columns created using plt.subplots().
A single subplot returns one Axes object, while multiple subplots may return a one-dimensional or two-dimensional NumPy array. One-dimensional arrays use a single index, and two-dimensional arrays use row and column indexes.
The squeeze parameter controls the shape of the returned
Axes object. Setting squeeze=False ensures that
Matplotlib always returns a two-dimensional Axes array, making
indexing consistent across different subplot layouts.
The ax.flat attribute and nested loops provide convenient
ways to access multiple Axes objects. These techniques are useful
when applying common formatting or creating dynamic subplot grids.
Understanding subplot indexing helps us build organized charts, dashboards and complex data visualizations with better control over every plotting area.