We adjust subplot spacing to make sure plots do not overlap and look neat. It helps in clear visualization when multiple plots are shown together.
Subplot spacing adjustment in Matplotlib
plt.subplots_adjust(left=None, right=None, top=None, bottom=None, wspace=None, hspace=None)
left, right, top, bottom control the margins of the whole figure (values between 0 and 1).
wspace and hspace control the width and height space between subplots (fraction of average subplot size).
plt.subplots_adjust(wspace=0.5, hspace=0.5)
plt.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.1)
plt.subplots_adjust(wspace=0.2)This code creates two figures with 2x2 subplots each. The first figure uses default spacing, which may look crowded. The second figure increases horizontal and vertical space between subplots for clarity.
import matplotlib.pyplot as plt fig, axs = plt.subplots(2, 2) for i, ax in enumerate(axs.flat, 1): ax.plot([1, 2, 3], [i, i*2, i*3]) ax.set_title(f'Plot {i}') # Default spacing plt.suptitle('Default spacing') plt.show() fig, axs = plt.subplots(2, 2) for i, ax in enumerate(axs.flat, 1): ax.plot([1, 2, 3], [i, i*2, i*3]) ax.set_title(f'Plot {i}') # Adjust spacing plt.subplots_adjust(wspace=0.5, hspace=0.7) plt.suptitle('Adjusted spacing') plt.show()
You can call plt.subplots_adjust() after creating subplots to change spacing anytime before showing the plot.
Values for spacing parameters are fractions of the figure or subplot size, so try small changes and see the effect.
Adjust subplot spacing to avoid overlapping and improve plot clarity.
Use plt.subplots_adjust() with parameters like wspace and hspace to control space between plots.
Margins can be controlled with left, right, top, and bottom.