How to set the spacing between subplots in Matplotlib in Python?
×


How to set the spacing between subplots in Matplotlib in Python?

4337

How to Control Spacing Between Subplots in Matplotlib

When plotting multiple subplots in Matplotlib, proper spacing is vital to keep your visuals neat and prevent overlaps. This tutorial walks you through several approaches to adjust the space between your subplots effectively.

Manual Spacing with subplots_adjust()

The subplots_adjust() function offers fine control over subplot layout by letting you define margins and gaps. You can tweak horizontal and vertical spaces as well as the padding from the figure edges.

import matplotlib.pyplot as plt

fig, axs = plt.subplots(2, 2, figsize=(8, 6))

# Set horizontal and vertical spacing between subplots
fig.subplots_adjust(wspace=0.4, hspace=0.6)

plt.show()

Here, wspace adjusts the width between columns, and hspace controls the height between rows.

Automatic Adjustment Using tight_layout()

If you want Matplotlib to manage subplot spacing automatically, tight_layout() comes in handy. It optimizes padding around subplots to minimize overlaps without manual tweaking.

import matplotlib.pyplot as plt

fig, axs = plt.subplots(2, 2, figsize=(8, 6))

plt.tight_layout()

plt.show()

This method is simple and often effective, especially when subplot content size varies.

Advanced Control with GridSpec

For complex subplot arrangements requiring precise spacing control, Matplotlib’s GridSpec class is ideal. It lets you specify spacing parameters along with the grid layout.

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

fig = plt.figure(figsize=(8, 6))

# Create a 2x2 grid with specified spacing
gs = gridspec.GridSpec(2, 2, wspace=0.3, hspace=0.5)

ax1 = fig.add_subplot(gs[0, 0])
ax2 = fig.add_subplot(gs[0, 1])
ax3 = fig.add_subplot(gs[1, :])

plt.show()

Using GridSpec, you get fine-grained control over the spacing between subplots as well as their relative placement.

Summary

Proper spacing between subplots is key to producing clean and professional visualizations in Matplotlib. Whether you prefer manual spacing with subplots_adjust(), automatic management via tight_layout(), or advanced layout control with GridSpec, Matplotlib has the tools to fit your needs.


If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!

For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!


Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat