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
How to increase the spacing between subplots in Matplotlib with subplot2grid?
To increase the spacing between subplots with subplot2grid, you can control the horizontal and vertical spacing using the wspace and hspace parameters. Here's how to create well-spaced subplots using GridSpec.
Basic Approach
The key steps are ?
Set the figure size and adjust the padding between and around the subplots
Create a grid layout using
GridSpecto place subplots within a figureUpdate the subplot parameters with
wspaceandhspacefor spacing controlAdd subplots to the current figure using
subplot2gridorplt.subplotDisplay the figure using
show()method
Example with GridSpec
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Create grid specification
gs = plt.GridSpec(2, 2)
gs.update(wspace=0.5, hspace=0.5) # Increase spacing
# Create subplots
ax1 = plt.subplot(gs[0, :]) # Top row, spanning both columns
ax2 = plt.subplot(gs[1, 0]) # Bottom left
ax3 = plt.subplot(gs[1, 1]) # Bottom right
# Add some sample data to visualize the spacing
ax1.plot([1, 2, 3], [1, 4, 2])
ax1.set_title('Top Subplot')
ax2.plot([1, 2, 3], [3, 1, 4])
ax2.set_title('Bottom Left')
ax3.plot([1, 2, 3], [2, 3, 1])
ax3.set_title('Bottom Right')
plt.show()
Using subplot2grid Directly
You can also use subplot2grid function directly with spacing parameters ?
import matplotlib.pyplot as plt
plt.figure(figsize=(8, 6))
# Using subplot2grid with spacing
ax1 = plt.subplot2grid((2, 2), (0, 0), colspan=2)
ax2 = plt.subplot2grid((2, 2), (1, 0))
ax3 = plt.subplot2grid((2, 2), (1, 1))
# Adjust spacing manually
plt.subplots_adjust(wspace=0.4, hspace=0.6)
# Add sample plots
ax1.bar(['A', 'B', 'C'], [3, 7, 2])
ax1.set_title('Bar Chart')
ax2.scatter([1, 2, 3, 4], [2, 5, 3, 8])
ax2.set_title('Scatter Plot')
ax3.pie([30, 45, 25], labels=['X', 'Y', 'Z'])
ax3.set_title('Pie Chart')
plt.show()
Spacing Parameters
| Parameter | Description | Range |
|---|---|---|
wspace |
Width spacing between subplots | 0.0 - 1.0+ |
hspace |
Height spacing between subplots | 0.0 - 1.0+ |
Conclusion
Use GridSpec.update() or plt.subplots_adjust() to control spacing between subplots. Higher wspace and hspace values create more space between plots, preventing overlap and improving readability.
