Matplotlib.pyplot.tight_layout() in Python
Last Updated :
23 Dec, 2024
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:
Python
import matplotlib.pyplot as plt
fig, ax = plt.subplots(3, 3)
plt.show()
Output:
9 subplots plottedYou 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.
Python
import matplotlib.pyplot as plt
fig, ax = plt.subplots(3, 3)
plt.tight_layout()
plt.show()
Output:
No overlapping in the plotsCreating 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.
Python
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:
Two-Paneled Figure using Matplotlib tight_layout() FunctionThe 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.
Python
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:
Side-by-Side Histograms with tight_layout()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.
Similar Reads
Matplotlib.pyplot.sci() in Python Matplotlib is a library in Python and it is numerical - mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot,
2 min read
Matplotlib.pyplot.ylim() in Python Matplotlib is a library in Python and it is numerical - mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. matplotlib.pyplot.ylim() Function The ylim() function in pyplot module of matplotlib library is used to g
2 min read
Matplotlib.pyplot.xlim() in Python Matplotlib is a library in Python and it is numerical - mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot,
2 min read
Matplotlib.pyplot.show() in Python Matplotlib is a library in Python and it is numerical - mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. Sample Code - Python3 1== # sample code import matplotlib.pyplot as plt plt.plot([1, 2, 3, 4], [16, 4, 1,
2 min read
Matplotlib.pyplot.yticks() in Python Matplotlib is a library in Python and it is numerical - mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. Matplotlib.pyplot.yticks() Function The annotate() function in pyplot module of matplotlib library is use
2 min read
Matplotlib.pyplot.sca() in Python Matplotlib is a library in Python and it is numerical â mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot,
1 min read
Matplotlib.figure.Figure.tight_layout() in Python Matplotlib is a library in Python and it is numerical â mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot
2 min read
Matplotlib.pyplot.locator_params() in Python Matplotlib is one of the most popular Python packages used for data visualization. It is a cross-platform library for making 2D plots from data in arrays.Pyplot is a collection of command style functions that make matplotlib work like MATLAB. Note: For more information, refer to Python Matplotlib â
2 min read
Matplotlib.pyplot.cla() in Python Matplotlib is a library in Python and it is numerical - mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot,
1 min read
Matplotlib.pyplot.gca() in Python Matplotlib is a library in Python and it is a numerical - mathematical extension for the NumPy library. Pyplot is a state-based interface to a Matplotlib module that provides a MATLAB-like interface.  matplotlib.pyplot.gca() Function The gca() function in pyplot module of matplotlib library is used
2 min read