Tight layout helps to automatically adjust the spacing between plot elements so nothing overlaps or gets cut off.
0
0
Tight layout for spacing in Matplotlib
Introduction
When your plot labels or titles are overlapping each other.
When parts of your plot are cut off in the saved image or display.
When you add multiple subplots and want them spaced nicely.
When you want to improve the overall neatness of your figure without manual adjustments.
Syntax
Matplotlib
plt.tight_layout(pad=1.08, h_pad=None, w_pad=None, rect=None)
pad controls the padding between the figure edge and the edges of subplots.
You call plt.tight_layout() after creating your plots but before showing or saving.
Examples
Basic example: applies tight layout to a simple plot.
Matplotlib
import matplotlib.pyplot as plt plt.plot([1, 2, 3], [4, 5, 6]) plt.tight_layout() plt.show()
Using tight layout with multiple subplots and increased padding.
Matplotlib
fig, axs = plt.subplots(2, 2) for i in range(2): for j in range(2): axs[i, j].set_title(f'Subplot {i},{j}') plt.tight_layout(pad=2.0) plt.show()
Sample Program
This program creates 4 subplots with titles and axis labels. Using plt.tight_layout() adjusts spacing so labels and titles do not overlap.
Matplotlib
import matplotlib.pyplot as plt fig, axs = plt.subplots(2, 2) for i in range(2): for j in range(2): axs[i, j].plot([1, 2, 3], [3*(i+j), 2*(i+j), i+j]) axs[i, j].set_title(f'Subplot {i},{j}') axs[i, j].set_xlabel('X axis') axs[i, j].set_ylabel('Y axis') plt.tight_layout(pad=1.5) plt.show()
OutputSuccess
Important Notes
If you still see overlapping, try increasing the pad value.
Tight layout may not work perfectly with some complex plot elements like legends outside the plot area.
Summary
Tight layout automatically adjusts spacing to prevent overlap.
Call plt.tight_layout() after creating plots but before showing or saving.
You can control padding with the pad parameter.