0
0
Matplotlibdata~5 mins

Constrained layout vs tight layout in Matplotlib

Choose your learning style9 modes available
Introduction

We use constrained layout and tight layout to make plots look neat and avoid overlapping parts like labels and titles.

When your plot labels or titles overlap and look messy.
When you want to automatically adjust spacing between subplots.
When you add legends or colorbars that might cover parts of the plot.
When you want a quick way to improve plot appearance without manual spacing.
When you have multiple subplots and want them arranged cleanly.
Syntax
Matplotlib
plt.tight_layout(pad=1.08, h_pad=None, w_pad=None, rect=None)

fig, ax = plt.subplots(constrained_layout=True)

tight_layout() is a function you call after creating plots.

constrained_layout is a figure option you set when creating the figure.

Examples
Using tight_layout() to adjust spacing after plot creation.
Matplotlib
import matplotlib.pyplot as plt

plt.plot([1, 2, 3], [4, 5, 6])
plt.title('Example')
plt.tight_layout()
plt.show()
Using constrained_layout=True when creating the figure to auto-adjust spacing.
Matplotlib
import matplotlib.pyplot as plt

fig, ax = plt.subplots(constrained_layout=True)
ax.plot([1, 2, 3], [4, 5, 6])
ax.set_title('Example')
plt.show()
Using constrained layout with multiple subplots to keep them neat.
Matplotlib
import matplotlib.pyplot as plt

fig, axs = plt.subplots(2, 2, constrained_layout=True)
for ax in axs.flat:
    ax.plot([1, 2, 3], [1, 4, 9])
    ax.set_title('Plot')
plt.show()
Sample Program

This code creates two plots. One uses tight_layout() to adjust spacing after plotting. The other uses constrained_layout=True when creating the figure. Both help avoid overlapping labels and titles.

Matplotlib
import matplotlib.pyplot as plt

# Create figure with tight_layout
fig1, ax1 = plt.subplots()
ax1.plot([1, 2, 3], [1, 4, 9])
ax1.set_title('Tight Layout Example')
plt.tight_layout()
plt.savefig('tight_layout_example.png')

# Create figure with constrained_layout
fig2, ax2 = plt.subplots(constrained_layout=True)
ax2.plot([1, 2, 3], [1, 4, 9])
ax2.set_title('Constrained Layout Example')
plt.savefig('constrained_layout_example.png')

print('Two plots created: one with tight_layout and one with constrained_layout.')
OutputSuccess
Important Notes

tight_layout() works well for simple plots but may fail with complex layouts.

constrained_layout is newer and better at handling complex subplot arrangements.

Sometimes you may need to tweak parameters or combine with manual adjustments for perfect results.

Summary

tight_layout() is a function to fix spacing after plot creation.

constrained_layout is a figure option that adjusts spacing automatically during creation.

Both help make plots look clean by preventing overlaps.