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
Selected Reading
How to make more than 10 subplots in a figure using Matplotlib?
Creating more than 10 subplots in a single figure is common when visualizing multiple datasets or comparing different plots. Matplotlib's subplots() function makes this straightforward by arranging plots in a grid layout.
Basic Grid Layout
Use nrows and ncols parameters to create a grid of subplots ?
import matplotlib.pyplot as plt
import numpy as np
# Set figure size for better visibility
plt.rcParams["figure.figsize"] = [12, 8]
plt.rcParams["figure.autolayout"] = True
# Create 4x3 grid (12 subplots)
rows = 4
cols = 3
fig, axes = plt.subplots(nrows=rows, ncols=cols)
# Add sample plots to each subplot
for i in range(rows):
for j in range(cols):
x = np.linspace(0, 10, 50)
y = np.sin(x + i + j)
axes[i, j].plot(x, y)
axes[i, j].set_title(f'Plot {i*cols + j + 1}')
plt.show()
Customizing Large Subplot Grids
For better organization with many subplots, adjust spacing and add meaningful titles ?
import matplotlib.pyplot as plt
import numpy as np
# Create 3x5 grid (15 subplots)
fig, axes = plt.subplots(3, 5, figsize=(15, 9))
# Sample data for demonstration
x = np.linspace(0, 2*np.pi, 100)
# Flatten axes for easier iteration
axes_flat = axes.flatten()
for i, ax in enumerate(axes_flat):
# Different function for each subplot
if i % 3 == 0:
y = np.sin(x * (i+1))
elif i % 3 == 1:
y = np.cos(x * (i+1))
else:
y = np.tan(x * (i+1) * 0.5)
ax.plot(x, y)
ax.set_title(f'Subplot {i+1}')
ax.grid(True)
# Adjust spacing between subplots
plt.tight_layout(pad=2.0)
plt.show()
Using subplot_mosaic for Complex Layouts
For irregular grid layouts with more than 10 subplots, use subplot_mosaic() ?
import matplotlib.pyplot as plt
import numpy as np
# Define complex layout with named subplots
mosaic = [
['A', 'A', 'B', 'C'],
['D', 'E', 'F', 'G'],
['H', 'I', 'J', 'K'],
['L', 'M', 'N', 'O']
]
fig, axes = plt.subplot_mosaic(mosaic, figsize=(12, 10))
# Add data to each named subplot
plot_names = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O']
x = np.linspace(0, 10, 50)
for i, name in enumerate(plot_names):
y = np.sin(x + i) * np.exp(-x/10)
axes[name].plot(x, y)
axes[name].set_title(f'Plot {name}')
plt.tight_layout()
plt.show()
Key Considerations
| Aspect | Recommendation | Reason |
|---|---|---|
| Figure Size | Increase proportionally | Prevents overcrowding |
| Spacing | Use tight_layout()
|
Avoids overlapping labels |
| Iteration | Flatten 2D axes array | Easier programming |
Conclusion
Use subplots(nrows, ncols) for regular grids with many subplots. Adjust figure size proportionally and use tight_layout() for proper spacing. Consider subplot_mosaic() for complex irregular layouts.
Advertisements
