Python

Use of Matplotlib’s Tight_Layout in Python

In Python, the Matplotlib module is a quantitative-mathematical expansion for the NumPy package. The Pyplot framework of the Matplotlib package offers a state-based system that enables MATLAB-like functionality. Line Graph, Gradient, Histogram, Dispersion, 3D Graph, and other graphs can be intended in Pyplot.

The tight_layout function in Matplotlib effectively resizes the subplot to incorporate within the plot region. It is an exploratory functionality that may or may not perform in all cases. It just evaluates the tick labels, axis labels, and titles’ extensiveness. We may utilize this tool to make interactive visualizations that could be viewed on every platform.

Let me quickly go through the parameters for the Matplotlib tight_layout before we get into instances.

Matplotlib tight_layout Parameters

The tight_layout function has three parameters:

  • Pad: It is the fractional spacing in between the graphic border and the border of subplots, e.g. floating number of font and size.
  • H_pad and w_pad: These parameters are used for spacing (length and width) along consecutive subplot borders, expressed as the ratio of the font and size. Pad is the default mode. These are an optional parameter.
  • rect: Tuple (top, left, right, bottom) that indicates a frame (top, left, right, bottom) in the adjusted graphic coordinates which will only accommodate the entire subplots region (containing labels). The standard setting is 0, 0, 1, and 1.

Using GridSpec with Matplotlib tight_layout

GridSpec contains a tight_layout() function of its own. Tight_layout() from the pyplot API however still runs. We can indicate the coordinates in which the subplots would be placed using the optional rect argument. To reduce overlapping, the tight_layout() method modifies the space among subplots.

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
fig = plt.figure(figsize =([8, 4]))
gs = gridspec.GridSpec(3, 6)
ax1 = plt.subplot(gs[1, :3])
ax1.set_ylabel('label 1', labelpad = 1, fontsize = 14)
ax1.plot([1, 2, 3], [3, 4.6, 5])
ax2 = plt.subplot(gs[0, 3:6])
ax2.set_ylabel('label 2', labelpad = 1, fontsize = 14)
ax2.plot([3, 4.4, 8], [3, 4.5, 5])
ax3 = plt.subplot(gs[2, 4:8])
ax3.set_ylabel('label 3', labelpad = 1, fontsize = 14)
ax3.plot([3.1, 5.4, 7.6, 4.9], [1.3, 4.4, 7, 3])
plt.tight_layout()
plt.show()

The dimensions must have been in standardized graphic parameters, with the default setting (0, 0, 1, and 1). Changing top and bottom can necessitate modifying hspace as well. We execute the tight_layout() function once again with a modified rect parameter to adjust hspace and vspace. The rect parameter provides the area that integrates the tick labels and other elements.

Matplotlib tight_layout() function using titles and captions

Titles and captions have been eliminated from the bounding region computations that determine the format before Matplotlib. These were once again used in the determination, but including them is not always advisable. Therefore, in this situation, lowering the axes to create the starting point for the plot is indicated.

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
plt.close('all')
fig = plt.figure()
fig, ax = plt.subplots(figsize=(6, 5))
lines = ax.plot(range(12), label='Plot')
ax.legend(bbox_to_anchor=(0.8, 0.4), loc='bottom left',)
fig.tight_layout()
plt.show()

In this instance, after integrating matpotlib.pyplot and matplotlib.gridspec libraries, we define the plt.figure() function. We indicate the range of lines drawn in the graph and give the tag ‘Plot’ to the graph. We also specify the location of the title of the graph.

Tight_layout Pad in Matplotlib

The spacing between both the graphic boundaries and the boundaries of the subplots will be modified. There is no data returned by this procedure. The tight_layout method in Matplotlib dynamically recreates a subplot to accommodate within the plot area.

import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots(2, 2)
data = np.arange(1.0, 40, 1.05)
x1= np.sin(data)
y1= np.cos(data)

x2= np.cos(data)
y2= np.tan(data)
x3= np.tan(data)
y3= np.exp(data*3)
x4= [4,15,20]
y4= [8,15,22]
ax[1, 1].plot(x1, y1)
ax[1, 0].plot(x2, y2)
ax[0, 1].plot(x3, y3)
ax[0, 0].plot(x4, y4)
ax[1, 1].set_title("figure 1 ")
ax[1, 0].set_title("figure 2")
ax[0, 1].set_title("figure 3")
ax[0, 0].set_title("figure 4")
plt.tight_layout(pad=4.5)
plt.show()

The padding attribute is being used to customize them. We integrate matplotlib.pyplot and the numpy library in this instance.

Next, we use the subplots () function to generate a chart and a sequence of subplots. In utilizing the plot () function, we specify the data dimensions for different subplots and display the datasets. Then the set_title() function is utilized to insert a tag line to every graph. In the end, we just utilize the plt.tight_layout () function to modify the spacing.

We provide pad as an attribute and set the value to 4.5 in one case and 1.0 in the other.

Matplotlib Tight_Layout Hspace

Here, we will see how to change the altitude within successive subplots’ margins. The h_pad argument is provided to the tight_layout() function to modify the height.

import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 2)
data = np.arange(1.0, 40, 1.5
x1= np.sin(data)
y1= np.cos(data)
x2= np.cos(data)
y2= np.tan(data)
ax[1].plot(x1, y1)
ax[0].plot(x2, y2)
ax[0].set_title("Figure 1 ")
ax[1].set_title("Figure 2")
plt.tight_layout(h_pad=1.2)

plt.show()

We include matplotlib.pyplot and the numpy library in this example. Utilizing the subplots() technique, we generate a chart and a collection of subplots. Furthermore, we utilize the plot() function to visualize the data and analyze the data dimensions for numerous subplots.

The set title () function is used to insert a caption to every graph. Now, we use plt.tight layout() function to modify the elevation between both the vertices. In both situations, we specify h_pad as an argument and set the value to 1.2 and 12.5 respectively.

Tight_layout intends to reorganize subplots in a graph such that axes elements and titles on the axes do not conflict.

Conclusion

We examined a few different methods to accomplish Matplotlib tight_layout in Python in this article. With the gridspec, labels, and illustrations, we explained how to use the tight_layout method. We could also utilize a tight_layout in association with color bars to make it look good in the graphic presentation.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content