Matplotlib tight_layout in Python with Examples

Hello programmers, in today’s article, we will discuss Matplotlib tight_layout in Python. Matplotlib library in Python is a numerical – mathematical extension for NumPy library. Pyplot module is a state-based interface of Matplotlib library which provides a MATLAB like features. Various plots that can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc.

The Matplotlib tight_layout automatically adjusts the subplot such that it fits into the figure area. This is an experimental feature and may not always work. It only checks the extents of ticklabels, axis labels, and titles. This feature allows you to create dynamic graphs that can be used on any device. Before we cite examples for the Matplotlib tight_layout, let me briefly brief you with the same syntax and parameters.

Syntax of Matplotlib tight_layout in Python

matplotlib.pyplot.tight_layout(pad=1.08, h_pad=None, w_pad=None, rect=None)

Parameters of Matplotlib tight_layout

  • pad: Padding between the figure edge and the edges of subplots, as a fraction, i.e., float value of the font size.
  • h_pad, w_pad: Padding (height/width) between edges of adjacent subplots, as a fraction, i.e., float of the font size. Defaults to pad. (Optional)
  • rect: Tuple (left, bottom, right, top) representing a rectangle (left, bottom, right, top) in the normalized figure coordinate that the whole subplots area (including labels) will fit into. Default is (0, 0, 1, 1).

Return type of Matplotlib tight_layout

This method does not return any value. The Matplotlib tight_layout function adjusts subplot such that it fits in to the figure area.

Example of Matplotlib tight_plot in 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') 
  
fig.legend((l1, l2), ('Line 1', 'Line 2'), 'upper left') 
fig.legend((l3, l4), ('Line 3', 'Line 4'), 'upper right') 
  
  
fig.suptitle('matplotlib.pyplot.tight_layout() Example') 
plt.tight_layout() 
plt.show() 

Output:

Example of Matplotlib tight_plot in Python

Explanation:

In matplotlib python, the location of axes including subplots, are specified in normalized figure coordinates. It can happen that your axis labels or titles or sometimes even ticklabels go outside the figure area, and are thus clipped. Thus to prevent this, the location of axes needs to be adjusted. Matplotlib introduces a new command tight_layout() that does this automatically for you. In order to perform this adjustment each time the figure is redrawn. You can call fig.set_tight_layout(True), or, equivalently, set the figure.autolayout rcParam to True. In the case of multiple subplots, often you see labels of different axes overlapping each other. Matplotlib tight_layout() function will also adjust the spacing between subplots to minimize the overlaps. In this example, the tight_plot function is called, which adjusts the labels and titles of the figure instead of clipping them.

Matplotlib tight_layout using GridSpec

import matplotlib.gridspec as gridspec

plt.close('all')
fig = plt.figure()

gs1 = gridspec.GridSpec(2, 1)
ax1 = fig.add_subplot(gs1[0])
ax2 = fig.add_subplot(gs1[1])

example_plot(ax1)
example_plot(ax2)

gs1.tight_layout(fig, rect=[0, 0, 0.5, 1])

Output:

Matplotlib tight_layout using GridSpec

Explanation:

GridSpec has its own tight_layout() method. The pyplot API tight_layout() also works. You may provide an optional rect parameter, which specifies the bounding box that the subplots will be fit inside. The coordinates must be in normalized figure coordinates and the default is (0, 0, 1, 1). Adjusting top and bottom may require adjustment of hspace also. To update hspace & vspace, we call tight_layout() again with an updated rect argument. Note that the rect argument specifies the area including the ticklabels, etc.

Matplotlib tight_layout with Legends and Annotations

import matplotlib.gridspec as gridspec

plt.close('all')
fig = plt.figure()

fig, ax = plt.subplots(figsize=(4, 3))
lines = ax.plot(range(10), label='A simple plot')
ax.legend(bbox_to_anchor=(0.7, 0.5), loc='center left',)
fig.tight_layout()
plt.show()

Output:

Legends and Annotations

Explanation:

In Pre Matplotlib 2.2 version, legends and annotations were excluded from the bounding box calculations that decide the layout. Subsequently, these were added to the calculation, but sometimes it is undesirable to include them. However, in this case, it might be good to have the axes shrinking a bit to make room for the legend.

Must Read

Working With Matplotlib Text in Python
Matplotlib Figsize | Change the Size of Graph using Figsize
Matplotlib Arrow() Function With Examples
How to Clear Plot in Matplotlib Using clear() Method

Conclusion

In this article, we have discussed various ways of implementing Matplotlib tight_layout in Python. We have learned using the tight_layout function with gridspec, legends, and annotations. You can also use tight_layout along with colorbars that adjust it so that it fits in the figure plot. Refer to this article in case of any doubt regarding the Matplotlib tught_layout.

However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.

Happy Pythoning!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments