Matplotlib is a powerful Python library for creating visualizations. When working with multiple subplots, effective spacing is crucial for readability. This article explores methods to control subplot spacing in Matplotlib.
Table of Contents
tight_layout()
Methodsubplots_adjust()
Methodsubplot_tool()
Methodconstrained_layout=True
Parameter
tight_layout()
Method
The tight_layout()
function is a simple and effective way to adjust subplot spacing. It automatically prevents overlapping elements like titles and labels. It’s ideal when you don’t need precise control over individual spacing parameters.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
fig, axes = plt.subplots(2, 1)
axes[0].plot(x, y1)
axes[0].set_title('Sine Wave')
axes[1].plot(x, y2)
axes[1].set_title('Cosine Wave')
plt.tight_layout()
plt.show()
subplots_adjust()
Method
For precise control, use plt.subplots_adjust()
. This function allows manipulation of spacing parameters: left
, bottom
, right
, top
, wspace
(width), and hspace
(height). These are fractions of the figure dimensions.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
fig, axes = plt.subplots(2, 1)
axes[0].plot(x, y1)
axes[0].set_title('Sine Wave')
axes[1].plot(x, y2)
axes[1].set_title('Cosine Wave')
plt.subplots_adjust(hspace=0.5)
plt.show()
Here, hspace=0.5
increases vertical spacing. Experiment with values to achieve your desired layout. Similarly adjust wspace
for horizontal spacing.
subplot_tool()
Method
plt.subplot_tool()
provides an interactive interface. It opens a window where you can drag and resize subplots visually. This is particularly helpful for complex layouts.
import matplotlib.pyplot as plt
fig, axes = plt.subplots(2, 2)
plt.subplot_tool()
plt.show()
constrained_layout=True
Parameter
A modern and robust approach is using constrained_layout=True
within plt.subplots()
. This automatically adjusts parameters to prevent overlaps, handling complex layouts more effectively than tight_layout()
.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
fig, axes = plt.subplots(2, 1, constrained_layout=True)
axes[0].plot(x, y1)
axes[0].set_title('Sine Wave')
axes[1].plot(x, y2)
axes[1].set_title('Cosine Wave')
plt.show()
This simplifies code and offers a reliable solution, especially for intricate figures. Choose the method best suited to your needs: tight_layout()
or constrained_layout=True
for simple adjustments; subplots_adjust()
for fine-grained control; and subplot_tool()
for interactive adjustments.