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
Changing Matplotlib subplot size/position after axes creation
In Matplotlib, you can change the size and position of subplots even after axes creation using GridSpec and position methods. This is useful when you need to dynamically adjust subplot layouts.
Steps to Change Subplot Size/Position
- Create a figure using
figure()method - Add an axes to the figure using
add_subplot() - Create a
GridSpeclayout for positioning subplots - Set the position using
set_position() - Update the subplot specification with
set_subplotspec() - Add additional subplots if needed
- Use
tight_layout()to adjust spacing
Example
Here's how to resize and reposition a subplot after creation ?
import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec # Set figure size plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True # Create figure and initial subplot fig = plt.figure() ax = fig.add_subplot(111) ax.plot([1, 2, 3, 4], [1, 4, 2, 3], 'bo-', label='Original') # Create GridSpec layout gs = gridspec.GridSpec(3, 1) # Change subplot position and size ax.set_position(gs[0:2].get_position(fig)) ax.set_subplotspec(gs[0:2]) # Add another subplot ax2 = fig.add_subplot(gs[2]) ax2.plot([1, 2, 3, 4], [3, 1, 4, 2], 'r^-', label='New subplot') fig.tight_layout() plt.show()
Understanding GridSpec Parameters
The GridSpec(3, 1) creates a 3×1 grid layout ?
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
fig = plt.figure(figsize=(8, 6))
# Create 2x2 grid
gs = gridspec.GridSpec(2, 2, hspace=0.3, wspace=0.2)
# Different positioning options
ax1 = fig.add_subplot(gs[0, :]) # Top row, all columns
ax2 = fig.add_subplot(gs[1, 0]) # Bottom left
ax3 = fig.add_subplot(gs[1, 1]) # Bottom right
ax1.plot([1, 2, 3], [1, 4, 2])
ax1.set_title('Spans entire top row')
ax2.plot([1, 2, 3], [2, 1, 3])
ax2.set_title('Bottom left')
ax3.plot([1, 2, 3], [3, 2, 1])
ax3.set_title('Bottom right')
plt.show()
Key Methods
| Method | Purpose | Usage |
|---|---|---|
set_position() |
Change subplot position | Updates axes location in figure |
set_subplotspec() |
Update subplot specification | Links axes to new GridSpec position |
GridSpec |
Create grid layout | Defines subplot arrangement |
Conclusion
Use GridSpec with set_position() and set_subplotspec() to dynamically change subplot layouts. This approach provides flexible control over subplot arrangement after axes creation.
Advertisements
