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 can I programmatically select a specific subplot in Matplotlib?
To programmatically select a specific subplot in Matplotlib, you can use several approaches including add_subplot(), subplots(), or subplot() methods. This allows you to modify individual subplots after creation.
Method 1: Using add_subplot()
Create subplots in a loop and then select a specific one by calling add_subplot() again with the same position ?
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [10, 4]
plt.rcParams["figure.autolayout"] = True
fig = plt.figure()
# Create 4 subplots
for index in [1, 2, 3, 4]:
ax = fig.add_subplot(1, 4, index)
ax.plot(np.random.rand(5), np.random.rand(5))
ax.set_title(f'Subplot {index}')
# Select and modify the 2nd subplot
ax = fig.add_subplot(1, 4, 2)
ax.plot(np.random.rand(5), np.random.rand(5), color='red', linewidth=3)
ax.set_title('Selected Subplot 2', color='red')
plt.show()
Method 2: Using subplots() with Array Indexing
Create all subplots at once and access them using array indexing ?
import numpy as np
import matplotlib.pyplot as plt
# Create subplots and get axes array
fig, axes = plt.subplots(2, 2, figsize=(8, 6))
# Plot on all subplots
for i in range(2):
for j in range(2):
axes[i, j].plot(np.random.rand(10))
axes[i, j].set_title(f'Subplot ({i},{j})')
# Select and modify specific subplot (top-right)
axes[0, 1].plot(np.random.rand(10), color='red', linewidth=3)
axes[0, 1].set_title('Selected Subplot', color='red')
axes[0, 1].set_facecolor('lightgray')
plt.tight_layout()
plt.show()
Method 3: Using plt.subplot()
Use plt.subplot() to switch between subplots programmatically ?
import numpy as np
import matplotlib.pyplot as plt
plt.figure(figsize=(12, 4))
# Create and plot on multiple subplots
for i in range(1, 4):
plt.subplot(1, 3, i)
plt.plot(np.random.rand(10))
plt.title(f'Subplot {i}')
# Select specific subplot (middle one) and add more data
plt.subplot(1, 3, 2)
plt.plot(np.random.rand(10), 'ro-', linewidth=2, markersize=8)
plt.title('Selected & Modified', color='red', fontweight='bold')
plt.grid(True)
plt.tight_layout()
plt.show()
Comparison
| Method | Best For | Access Pattern |
|---|---|---|
add_subplot() |
Dynamic subplot creation | Position-based selection |
subplots() |
Grid layouts with easy access | Array indexing |
plt.subplot() |
Sequential plotting workflow | Position switching |
Conclusion
Use subplots() with array indexing for grid layouts where you need frequent access to specific subplots. Use add_subplot() or plt.subplot() for dynamic subplot selection and modification.
Advertisements
