Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Populating Matplotlib subplots through a loop and a function
Matplotlib subplots can be efficiently populated using loops and functions to create organized grid layouts. This approach is especially useful when you need to display multiple related plots with similar formatting.
Creating the Subplot Grid
First, let's set up a 3×2 grid of subplots and define our plotting function ?
import numpy as np
import matplotlib.pyplot as plt
# Set figure size and layout
plt.rcParams["figure.figsize"] = [10, 8]
plt.rcParams["figure.autolayout"] = True
# Create 3 rows and 2 columns of subplots
fig, axes = plt.subplots(3, 2)
def iterate_columns(cols, x, color='red'):
"""Plot data across all columns in a row"""
for col in cols:
col.plot(x, color=color)
col.grid(True, alpha=0.3)
# Generate and plot data for each row
for i, row in enumerate(axes):
# Create random walk data for each row
x = np.random.normal(0, 1, 100).cumsum()
# Use different colors for each row
colors = ['red', 'blue', 'green']
iterate_columns(row, x, color=colors[i])
plt.tight_layout()
plt.show()
Enhanced Version with Titles and Customization
Here's an improved version with subplot titles and better organization ?
import numpy as np
import matplotlib.pyplot as plt
def populate_subplot(ax, data, title, color='blue'):
"""Populate a single subplot with data and formatting"""
ax.plot(data, color=color, linewidth=2)
ax.set_title(title, fontsize=10, pad=10)
ax.grid(True, alpha=0.3)
ax.set_xlabel('Time Steps')
ax.set_ylabel('Value')
# Create subplot grid
fig, axes = plt.subplots(2, 3, figsize=(12, 6))
# Data types and colors for different plots
plot_configs = [
('Random Walk', 'blue'),
('Sine Wave', 'red'),
('Exponential', 'green'),
('Cosine Wave', 'orange'),
('Linear Trend', 'purple'),
('Noise', 'brown')
]
# Flatten axes array for easier iteration
axes_flat = axes.flatten()
for i, (title, color) in enumerate(plot_configs):
# Generate different types of data
if 'Random' in title:
data = np.random.normal(0, 1, 100).cumsum()
elif 'Sine' in title:
data = np.sin(np.linspace(0, 4*np.pi, 100))
elif 'Exponential' in title:
data = np.exp(np.linspace(0, 2, 100))
elif 'Cosine' in title:
data = np.cos(np.linspace(0, 4*np.pi, 100))
elif 'Linear' in title:
data = np.linspace(0, 10, 100) + np.random.normal(0, 0.5, 100)
else: # Noise
data = np.random.normal(0, 1, 100)
# Populate the subplot
populate_subplot(axes_flat[i], data, title, color)
plt.tight_layout()
plt.show()
Key Features
| Feature | Purpose | Code Example |
|---|---|---|
| plt.subplots() | Creates subplot grid | fig, axes = plt.subplots(3, 2) |
| Loop iteration | Automates subplot population | for row in axes: |
| Function approach | Reusable plotting logic | def iterate_columns(cols, x): |
| plt.tight_layout() | Prevents subplot overlap | plt.tight_layout() |
Common Use Cases
This technique is particularly useful for:
Time series analysis − Displaying multiple data streams
Parameter studies − Showing results with different settings
Comparative analysis − Side-by-side plot comparisons
Data exploration − Quick visualization of multiple variables
Conclusion
Using loops and functions to populate matplotlib subplots provides an efficient way to create organized multi-plot displays. This approach reduces code duplication and makes it easy to apply consistent formatting across multiple subplots.
---