0
0
Matplotlibdata~5 mins

Subplot spacing adjustment in Matplotlib

Choose your learning style9 modes available
Introduction

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.

When you have multiple plots in one figure and their titles or labels overlap.
When you want to add more space between plots for better readability.
When the default spacing makes the plots look crowded or cluttered.
When you want to control the margins around the plots.
When adding annotations or legends that need extra space.
Syntax
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).

Examples
Adds more space between subplots horizontally and vertically.
Matplotlib
plt.subplots_adjust(wspace=0.5, hspace=0.5)
Sets the margins of the figure to leave space around the edges.
Matplotlib
plt.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.1)
Increases horizontal space between subplots only.
Matplotlib
plt.subplots_adjust(wspace=0.2)
Sample Program

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.

Matplotlib
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()
OutputSuccess
Important Notes

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.

Summary

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.