What does axes.flat in Matplotlib do?

The axes.flat property in Matplotlib provides a 1D iterator over a 2D array of subplots. This is particularly useful when you have multiple subplots arranged in rows and columns, and you want to iterate through them sequentially without worrying about their 2D structure.

Understanding axes.flat

When you create subplots using plt.subplots(nrows, ncols), the returned axes object is a 2D NumPy array. The axes.flat property flattens this 2D array into a 1D iterator, making it easier to loop through all subplots ?

Basic Example

Here's how to use axes.flat to plot the same data across multiple subplots ?

import numpy as np
import matplotlib.pyplot as plt

# Set figure properties
plt.rcParams["figure.figsize"] = [10, 6]
plt.rcParams["figure.autolayout"] = True

# Create subplots
fig, axes = plt.subplots(nrows=2, ncols=3)

# Generate sample data
x = np.linspace(0, 10, 50)
y = np.sin(x)

# Use axes.flat to iterate through all subplots
for i, ax in enumerate(axes.flat):
    ax.plot(x, y + i * 0.5)
    ax.set_title(f'Subplot {i+1}')
    ax.grid(True, alpha=0.3)

plt.show()

Comparison: With and Without axes.flat

Method Code Structure Best For
Without axes.flat Nested loops: for i in range(rows): for j in range(cols) When you need row/column indices
With axes.flat Single loop: for ax in axes.flat Simple iteration through all subplots

Practical Example with Different Data

Here's a more practical example showing different mathematical functions on each subplot ?

import numpy as np
import matplotlib.pyplot as plt

# Create figure and subplots
fig, axes = plt.subplots(2, 2, figsize=(10, 8))

# Define different functions
functions = [np.sin, np.cos, np.tan, np.exp]
labels = ['sin(x)', 'cos(x)', 'tan(x)', 'exp(x/5)']
x = np.linspace(0, 2*np.pi, 100)

# Plot different functions using axes.flat
for ax, func, label in zip(axes.flat, functions, labels):
    if label == 'exp(x/5)':
        y = func(x/5)  # Scale for exponential
    elif label == 'tan(x)':
        y = np.clip(func(x), -10, 10)  # Clip tan values
    else:
        y = func(x)
    
    ax.plot(x, y, linewidth=2)
    ax.set_title(label)
    ax.grid(True, alpha=0.3)

plt.tight_layout()
plt.show()

Key Benefits

  • Simplified iteration: No need for nested loops when you don't need row/column indices

  • Cleaner code: More readable than indexing with [i, j]

  • Flexible: Works with any subplot arrangement (2x3, 3x2, etc.)

Conclusion

The axes.flat property simplifies subplot iteration by converting a 2D axes array into a 1D iterator. Use it when you need to apply the same operations to all subplots sequentially, making your code cleaner and more readable.

Updated on: 2026-03-25T21:18:34+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements