How to Adjust Spacing Between Matplotlib Subplots


Often you may use subplots to display multiple plots alongside each other in Matplotlib. Unfortunately, these subplots tend to overlap each other by default.

The easiest way to resolve this issue is by using the Matplotlib tight_layout() function. This tutorial explains how to use this function in practice.

Create Subplots

Consider the following arrangement of 4 subplots in 2 columns and 2 rows:

import matplotlib.pyplot as plt

#define subplots
fig, ax = plt.subplots(2, 2)

#display subplots 
plt.show()

Notice how the subplots overlap each other a bit.

Adjust Spacing of Subplots Using tight_layout()

The easiest way to resolve this overlapping issue is by using the Matplotlib tight_layout() function:

import matplotlib.pyplot as plt

#define subplots
fig, ax = plt.subplots(2, 2)
fig.tight_layout()

#display subplots 
plt.show()

Adjust spacing of Matplotlib subplots

Adjust Spacing of Subplot Titles

In some cases you may also have titles for each of your subplots. Unfortunately even the tight_layout() function tends to cause the subplot titles to overlap:

import matplotlib.pyplot as plt

#define subplots
fig, ax = plt.subplots(2, 2)
fig.tight_layout()

#define subplot titles
ax[0, 0].set_title('First Subplot')
ax[0, 1].set_title('Second Subplot')
ax[1, 0].set_title('Third Subplot')
ax[1, 1].set_title('Fourth Subplot')

#display subplots 
plt.show()

Subplots with titles in Matplotlib

The way to resolve this issue is by increasing the height padding between subplots using the h_pad argument:

import matplotlib.pyplot as plt

#define subplots
fig, ax = plt.subplots(2, 2)
fig.tight_layout(h_pad=2)

#define subplot titles
ax[0, 0].set_title('First Subplot')
ax[0, 1].set_title('Second Subplot')
ax[1, 0].set_title('Third Subplot')
ax[1, 1].set_title('Fourth Subplot')

#display subplots 
plt.show()

Matplotlib subplot title spacing

Adjust Spacing of Overall Title

If you have an overall title, you can use the subplots_adjust() function to ensure that it doesn’t overlap with the subplot titles:

import matplotlib.pyplot as plt

#define subplots
fig, ax = plt.subplots(2, 2)
fig.tight_layout(h_pad=2)

#define subplot titles
ax[0, 0].set_title('First Subplot')
ax[0, 1].set_title('Second Subplot')
ax[1, 0].set_title('Third Subplot')
ax[1, 1].set_title('Fourth Subplot')

#add overall title and adjust it so that it doesn't overlap with subplot titles
fig.suptitle('Overall Title')
plt.subplots_adjust(top=0.85)

#display subplots 
plt.show()

Title spacing in Matplotlib

You can find more Matplotlib tutorials here.

Leave a Reply

Your email address will not be published.