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 get the list of axes for a figure in Pyplot?
In Matplotlib, you can retrieve all axes objects from a figure using the get_axes() method. This returns a list containing all axes in the figure, which is useful for programmatically manipulating multiple subplots.
Basic Example with Single Axes
Let's start with a simple example that creates a figure with one subplot and retrieves its axes ?
import numpy as np
import matplotlib.pyplot as plt
# Create data
xs = np.linspace(1, 10, 10)
ys = np.tan(xs)
# Create figure and add subplot
fig = plt.figure(figsize=(8, 4))
ax = fig.add_subplot(111)
# Get axes using get_axes() method
axes_list = fig.get_axes()
print(f"Number of axes: {len(axes_list)}")
print(f"Axes object: {axes_list[0]}")
# Set labels using the retrieved axes
axes_list[0].set_xlabel("X-Axis")
axes_list[0].set_ylabel("Y-Axis")
axes_list[0].set_title("Using get_axes() Method")
# Plot the data
ax.plot(xs, ys, color='red', linewidth=2)
plt.show()
Number of axes: 1 Axes object: <AxesSubplot:>
Multiple Subplots Example
The get_axes() method becomes more useful when working with multiple subplots ?
import numpy as np
import matplotlib.pyplot as plt
# Create data
x = np.linspace(0, 2*np.pi, 100)
# Create figure with multiple subplots
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
# Plot on both subplots
ax1.plot(x, np.sin(x), 'b-', label='sin(x)')
ax2.plot(x, np.cos(x), 'r-', label='cos(x)')
# Get all axes and set properties
axes_list = fig.get_axes()
print(f"Total axes in figure: {len(axes_list)}")
# Set titles for all axes programmatically
titles = ['Sine Function', 'Cosine Function']
for i, ax in enumerate(axes_list):
ax.set_title(titles[i])
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.grid(True)
ax.legend()
plt.tight_layout()
plt.show()
Total axes in figure: 2
Practical Use Cases
Here are common scenarios where get_axes() is particularly useful ?
import matplotlib.pyplot as plt
import numpy as np
# Create a complex figure with multiple subplots
fig = plt.figure(figsize=(12, 8))
# Add different subplot configurations
ax1 = fig.add_subplot(2, 2, 1)
ax2 = fig.add_subplot(2, 2, 2)
ax3 = fig.add_subplot(2, 1, 2)
# Sample data
x = np.linspace(0, 10, 50)
ax1.plot(x, x**2, 'g-')
ax2.scatter(x[::5], (x[::5])**0.5, c='purple')
ax3.bar(range(5), [1, 3, 2, 5, 4])
# Get all axes and apply common formatting
all_axes = fig.get_axes()
print(f"Figure contains {len(all_axes)} axes")
# Apply common styling to all axes
for i, ax in enumerate(all_axes):
ax.set_title(f'Subplot {i+1}')
ax.grid(True, alpha=0.3)
# Set specific properties for each axes
labels = ['X values', 'X values', 'Categories']
for ax, label in zip(all_axes, labels):
ax.set_xlabel(label)
plt.tight_layout()
plt.show()
Figure contains 3 axes
Key Points
-
fig.get_axes()returns a list of all axes objects in the figure - The list order corresponds to the order in which axes were added to the figure
- This method works with any subplot configuration (regular grids, custom layouts)
- Useful for programmatically applying settings to multiple subplots
- Each axes object in the list is fully functional for plotting and customization
Conclusion
The get_axes() method provides a convenient way to retrieve all axes from a figure as a list. This is especially useful for programmatically managing multiple subplots and applying common formatting across all axes in a figure.
Advertisements
