Subplots are used to plot multiple plots in a single figure. In Python’s Matplotlib, subplots are used comparative data visualization. Each subplot operates independently, but they share the same figure canvas.

By default, Matplotlib leaves some amount of space between subplots to ensure that axis labels and titles don’t overlap. In some scenarios, these gaps can be seen. For example, creating a grid of images or when axis labels are not necessary. In this scenario, it will be a waste of space.

Following are the several methods to remove gaps between the subplots

Adjusting Subplot Parameters with subplots_adjust

In Matplotlib, using the subplots_adjust function, we can manually adjust the spacing between the subplots.

import matplotlib.pyplot as plt

fig, axs = plt.subplots(2, 2)
plt.subplots_adjust(wspace=0, hspace=0)
plt.show()

In the above example, wspace and hspace are set to 0 to remove the space between subplots horizontally and vertically.

Using tight_layout for Automatic Adjustment

The tight_layout method automatically adjusts subplot params so that the subplot fits into the figure area.

import matplotlib.pyplot as plt

fig, axs = plt.subplots(2, 2)
plt.tight_layout(pad=0)
plt.show()

The pad parameter in the above example controls the padding between the subplots and can be set to 0 for no space.

Using GridSpec for Advanced Grid Customization

For more complex subplot arrangements, GridSpec provides sophisticated subplot placement. This method is useful when we need different subplot sizes or more control over their placement.

Following is the example:

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

fig = plt.figure()
gs = gridspec.GridSpec(2, 2, wspace=0, hspace=0)
axs = [fig.add_subplot(gs[i]) for i in range(4)]
plt.show()

Categorized in:

Tagged in: