We use constrained layout and tight layout to make plots look neat and avoid overlapping parts like labels and titles.
Constrained layout vs tight layout in 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.
tight_layout() to adjust spacing after plot creation.import matplotlib.pyplot as plt plt.plot([1, 2, 3], [4, 5, 6]) plt.title('Example') plt.tight_layout() plt.show()
constrained_layout=True when creating the figure to auto-adjust spacing.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()
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()
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.
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.')
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.
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.