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 remove the space between subplots in Matplotlib.pyplot?
Matplotlib creates default spacing between subplots for readability, but sometimes you need to remove this space entirely for seamless visualizations. Python provides several methods to achieve this using subplots_adjust(), GridSpec, and tight_layout().
Method 1: Using subplots_adjust()
The simplest approach is to set spacing parameters to zero using subplots_adjust() ?
import matplotlib.pyplot as plt
import numpy as np
fig, axes = plt.subplots(2, 2, figsize=(8, 6))
# Remove space between subplots
plt.subplots_adjust(wspace=0, hspace=0)
# Add sample data to each subplot
for i, ax in enumerate(axes.flat):
ax.plot(np.random.randn(10))
ax.set_title(f'Plot {i+1}')
plt.show()
Method 2: Using GridSpec
GridSpec provides more control over subplot positioning and spacing ?
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import numpy as np
fig = plt.figure(figsize=(8, 6))
gs = gridspec.GridSpec(2, 2, wspace=0, hspace=0)
for i in range(4):
ax = fig.add_subplot(gs[i])
ax.plot(np.random.randn(10))
ax.set_title(f'Plot {i+1}')
plt.show()
Method 3: Complete Space Removal
For completely seamless subplots without any borders or spacing ?
import matplotlib.pyplot as plt
import numpy as np
fig, axes = plt.subplots(2, 2, figsize=(8, 6))
# Remove all spacing and padding
plt.subplots_adjust(left=0, right=1, top=1, bottom=0, wspace=0, hspace=0)
# Remove axes and create seamless plots
for ax in axes.flat:
ax.imshow(np.random.rand(10, 10), cmap='viridis')
ax.axis('off') # Remove axes for seamless appearance
plt.show()
Parameters Explanation
| Parameter | Description | Range |
|---|---|---|
wspace |
Width spacing between subplots | 0.0 - 1.0 |
hspace |
Height spacing between subplots | 0.0 - 1.0 |
left/right |
Margin from figure edges | 0.0 - 1.0 |
top/bottom |
Margin from figure edges | 0.0 - 1.0 |
Comparison
| Method | Best For | Flexibility |
|---|---|---|
subplots_adjust() |
Simple spacing removal | Medium |
GridSpec |
Complex subplot arrangements | High |
tight_layout() |
Automatic optimal spacing | Low |
Conclusion
Use subplots_adjust(wspace=0, hspace=0) for simple space removal. For complex layouts, use GridSpec with zero spacing parameters. Set axis('off') for completely seamless visualizations.
Advertisements
