Matplotlib.pyplot.tight_layout() in Python
When working with Matplotlib, it's common to create subplots to showcase multiple graphs side by side. However, these subplots can sometimes overlap, making them difficult to read.
Creating Subplots using Matplotlib
Let's create a simple subplot:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(3, 3)
plt.show()
Output:

You can easily notice that how these subplots overlap each other a little bit.
Fortunately, Matplotlib's tight_layout()
function provides a simple solution to automatically adjust subplot parameters and ensure that the plots are neatly spaced with no overlap.
What is Matplotlib.pyplot.tight_layout()?
The tight_layout()
function in Matplotlib adjusts the subplot parameters so that the subplots fit within the figure area, ensuring that axes labels, titles, and other plot elements do not overlap. This function helps in creating visually appealing, organized plots, especially when multiple plots are displayed side-by-side.
Syntax: matplotlib.pyplot.tight_layout()
Let's first create a simple subplot grid and apply tight_layout() to ensure no overlap between the subplots.
import matplotlib.pyplot as plt
fig, ax = plt.subplots(3, 3)
plt.tight_layout()
plt.show()
Output:

Creating a Two-Paneled Figure using Matplotlib tight_layout() Function
You can also use tight_layout() when creating multiple plots in a single figure. Here's an example where we create two side-by-side plots using tight_layout() to ensure a clean layout.
import numpy as np
import matplotlib.pyplot as plt
fig, axs = plt.subplots(1, 2)
x = np.arange(0.0, 2.0, 0.02)
y1 = np.sin(2 * np.pi * x)
y2 = np.exp(-x)
l1, = axs[0].plot(x, y1)
l2, = axs[0].plot(x, y2, marker='o')
y3 = np.sin(4 * np.pi * x)
y4 = np.exp(-2 * x)
l3, = axs[1].plot(x, y3, color='tab:green')
l4, = axs[1].plot(x, y4, color='tab:red', marker='o')
axs[0].legend([l1, l2], ['Line 1', 'Line 2'], loc='upper left')
axs[1].legend([l3, l4], ['Line 3', 'Line 4'], loc='upper right')
fig.suptitle('matplotlib.pyplot.tight_layout() Example')
plt.tight_layout()
plt.show()
Output:

The output graph represent neat two-paneled figure with properly arranged legends, titles, and axes labels.
Side-by-Side Histograms with tight_layout()
Another practical application of tight_layout() is when visualizing multiple histograms. Here's an example where we plot two histograms of random data with adjustable bin sizes and use tight_layout() to ensure there is no overlap.
import numpy as np
import matplotlib.pyplot as plt
data1 = np.random.randn(1000)
data2 = np.random.randn(1000)
fig, axs = plt.subplots(1, 2, figsize=(10, 5))
axs[0].hist(data1, bins=30, color='blue', edgecolor='black')
axs[0].set_title('Histogram 1')
axs[0].set_xlabel('Value')
axs[0].set_ylabel('Frequency')
axs[1].hist(data2, bins=30, color='green', edgecolor='black')
axs[1].set_title('Histogram 2')
axs[1].set_xlabel('Value')
axs[1].set_ylabel('Frequency')
plt.tight_layout()
plt.show()
Output:

Output represents two neatly spaced histograms with labels, titles, and axes properly arranged.
Conclusion
Matplotlib's tight_layout()
function is particularly useful when:
- You have multiple subplots that might overlap.
- You want to ensure that titles, labels, and legends don't collide.
- You are working with complex figures that contain several visual elements.
By using tight_layout()
, you can ensure that your plots are clear and easy to interpret, enhancing the overall presentation of your data.