Matplotlib tight_layout – Helpful tutorial

In this Python Matplotlib tutorial, we will discuss Matplotlib tight_layout in python. Here we will cover different examples related to the tight_layout using matplotlib. And we will also cover the following topics:

  • Matplotlib tick_layout
  • Matplotlib tight_layout example
  • Matplotlib tight_layout pad
  • Matplotlib tight_layout hspace
  • Matplotlib tight_layout wspace
  • Matplotlib tight_layout rect
  • Matplotlib tight_layout savefig
  • Matplotlib tight_layout subplots
  • Matplotlib tight_layout suptitle
  • Matplotlib tight_layout cuts labels
  • Matplotlib tight_layout legend
  • Matplotlib tight_layout bbox
  • Matplotlib tight_layout not applied
  • Matplotlib tight_layout rcparams
  • Matplotlib imshow tight_layout
  • Matplotlib tight_layout gridspec
  • Matplotlib tight_layout colorbar
  • Matplotlib table tight_layout
  • Matplotlib scatter tight_layout
  • Matplotlib 3d plot tight layout
  • Matplotlib undo tight_layout
  • Matplotlib tight_layout alternative
  • Matplotlib constrained_layout vs tight_layout

Matplotlib tick_layout

In this section, we learn about the tick_layout() function in the pyplot module of matplotlib in Python. The tick_layout method is used to automatically adjust the subplot. Or we can say that this method is used to adjust the padding between and around the subplot.

The syntax is given below:

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

The following are the parameters used above:

ParameterValueDefault ValueDescription
padfloat1.08This parameter is used to specify padding between the figure edge and the edges of subplots, as a fraction of the font size.
h_pad, w_padfloat padThis parameter is used to specify height or weight between edges of the adjacent subplots, as a fraction of the font size.
recttuple(left, bottom, right, top)(0, 0, 1, 1)This parameter is used to specify a rectangle in normalized figure coordinates into which the whole subplots area including labels will fit.
tight_layout

Different cases where we use tight_layout() function:

  • When axis label or title go outside of the figure area.
  • When axis label or title of different subplots overlaps each other.
  • When we have multiple subplots in the figure area, and each of them is of a different size.
  • When we want to adjust extra padding around the figure and between the subplot.

Read Python Matplotlib tick_params + 29 examples

Matplotlib tight_layout example

Sometimes In the case of multiple subplots, we see that ticklabels, labels, titles, legends, etc overlapping each other.

In matplotlib to avoid overlapping or we can say that to adjust the spacing between subplots we can use the tight_layout() function.

The main aim of this function (tight_layout) is to minimize the overlaps instead of clipping them.

Let’s see an example:

Code #1: Normal Plot

# Import Library

import numpy as np 
import matplotlib.pyplot as plt 
 
# Create figure and subplot

fig, ax = plt.subplots(1, 2) 

# Define  Data

x = np.arange(0.0, 30.0 , 0.02) 
y1 = np.sin(x) 
y2 = np.exp(-x) 

# PLot Subplot 1

ax[0].plot(x, y1, label='Line1') 
ax[0].plot(x, y2, marker ='o', label='Line2') 

# Add legend

ax[0].legend(loc='upper left')

# Define Data

y3 = np.tan(x) 
y4 = np.exp(-2 * x) 

# plot subplot 2

ax[1].plot(x, y3, color ='cyan', label='Line3') 
ax[1].plot(x, y4, color ='tab:red', marker ='o', label='Line4') 

# Add legend

ax[1].legend(loc='upper right')

# Show

plt.show() 
  • In the above example, we import matplotlib.pyplot and numpy package.
  • Following this, we create a figure and set of subplots, using the subplots() method.
  • After that, we define the data coordinates for subplot 1 and subplot 2, and plot the data using the plot() method.
  • To place the legend for each subplot we add labels and to activate labels for each curve, we use the legend() method.
  • To display the figure, use the show() method.
matplotlib tight_layout example
Normal PLot

The above Code#1 is just a simple matplotlib subplot code in which we have multiple subplots in a figure area.

Code #2: tight_layout

# Import Library

import numpy as np 
import matplotlib.pyplot as plt 
 
# Create figure and subplot

fig, ax = plt.subplots(1, 2) 

# Define  Data

x = np.arange(0.0, 30.0 , 0.02) 
y1 = np.sin(x) 
y2 = np.exp(-x) 

# PLot Subplot 1

ax[0].plot(x, y1, label='Line1') 
ax[0].plot(x, y2, marker ='o', label='Line2') 

# Add legend

ax[0].legend(loc='upper left')

# Define Data

y3 = np.tan(x) 
y4 = np.exp(-2 * x) 

# Plot subplot 2

ax[1].plot(x, y3, color ='cyan', label='Line3') 
ax[1].plot(x, y4, color ='tab:red', marker ='o', label='Line4') 

# Add legend

ax[1].legend(loc='upper right')

# tight_layout

plt.tight_layout() 

# Show

plt.show() 

In this example, we also use the tight_layout() function to adjust the ticklabels of the figure instead of cutting them.

matplotlib tight_layout
tight_layout()

In the above Code#2, we have to implement the tight_layout() function.

Read Matplotlib x-axis label

Matplotlib tight_layout pad

We’ll learn how to adjust padding between the figure edges and the edges of the subplots. To adjust them we use the pad parameter.

The following is the syntax:

matplotlib.pyplot.tight_layout(pad=1.08)

Example:

# Import Libraries

import numpy as np
import matplotlib.pyplot as plt

# Create figure and subplot

fig, ax = plt.subplots(2, 2)

# Define Data

data = np.arange(0.0, 30, 0.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*2)

x4= [5,10,15]
y4= [6,12,18]

# Plot curves or subplots

ax[0, 0].plot(x1, y1)
ax[0, 1].plot(x2, y2)
ax[1, 0].plot(x3, y3)
ax[1, 1].plot(x4, y4)

# Add title to graph

ax[0, 0].set_title("Graph 1 ")
ax[0, 1].set_title("Graph 2")
ax[1, 0].set_title("Graph 3")
ax[1, 1].set_title("Graph 4")

# tight_layout

plt.tight_layout(pad=3.68)

# Show

plt.show()
  • In the above example, we import matplotlib.pyplot and numpy package.
  • Following this, we create a figure and set of subplots, using the subplots() method.
  • After that, we define the data coordinates for multiple subplots, and plot the data using the plot() method.
  • By using set_title() method we add title to each plot.
  • To adjsut the padding, use the plt.tight_layout() method. We pass pad as parameter and assign them 3.68 and 5.86 as value in respective cases.
matplotlib tight_layout pad
plt.tight_layout(pad=3.68)
matplotlib tight_layout padding
plt.tight_layout(pad=5.86)

Read Matplotlib multiple bar chart

Matplotlib tight_layout hspace

We’ll learn how to adjust the height between the edges of the adjacent subplots. To adjust the height we pass the h_pad parameter to the tight_layout() method.

The following is the syntax:

matplotlib.tight_layout(h_pad=None)

Let’s have a look at an example:

# Import Libraries

import numpy as np
import matplotlib.pyplot as plt

# Create figure and subplot

fig, ax = plt.subplots(2, 1)

# Define Data

data = np.arange(0.0, 30, 0.05)

x1= np.sin(data) 
y1= np.cos(data)

x2= np.cos(data)
y2= np.tan(data)

# Plot curves or subplots

ax[0].plot(x1, y1)
ax[1].plot(x2, y2)

# Add title to graph

ax[0].set_title("Graph 1 ")
ax[1].set_title("Graph 2")

# tight_layout

plt.tight_layout(h_pad=0.2)

# Show

plt.show()
  • In the above example, we import matplotlib.pyplot and numpy package.
  • After this, we create a figure and set of subplots, using the subplots() method.
  • We define the data coordinates for multiple subplots, and plot the data using the plot() method.
  • By using set_title() method we add title to each plot.
  • To adjsut the height between the edges, use the plt.tight_layout() method. We pass h_pad as parameter and assign them 1.5 and 15.5 as value in respective cases.
matplotlib tight_layout h_pad
tight_layout(h_pad=1.5)
matplotlib tight_layout height
tight_layout(h_pad=15.5)

Read Matplotlib scatter plot legend

Matplotlib tight_layout wspace

We’ll learn how to adjust the width between the edges of the adjacent subplots. To adjust the width we pass the w_pad parameter to the tight_layout() method.

The following is the syntax:

matplotlib.tight_layout(w_pad=None)

Let’s have a look at an example:

# Import Libraries

import numpy as np
import matplotlib.pyplot as plt

# Create figure and subplot

fig, ax = plt.subplots(1, 2)

# Define Data

data = np.arange(0.0, 30, 0.05)

x1= np.sin(data) 
y1= np.cos(data)

x2= np.exp(data*2)
y2= np.tan(data)

# Plot curves or subplots

ax[0].plot(x1, y1)
ax[1].plot(x2, y2)

# Add title to graph

ax[0].set_title("Graph 1 ")
ax[1].set_title("Graph 2")

# tight_layout

plt.tight_layout(w_pad=5.5)

# Show

plt.show()
  • In the above example, we import matplotlib.pyplot and numpy package.
  • After this, we create a figure and set of subplots, using the subplots() method.
  • We define the data coordinates for multiple subplots, and plot the data using the plot() method.
  • By using set_title() method we add title to each plot.
  • To adjsut the width between the edges, use the plt.tight_layout() method. We pass w_pad as parameter and assign them 5.5 value.
matplotlib tight_layout w_pad
tight_layout()

Here we use tight_layout() method without w_pad parameter.

matplotlib tight_layout width
plt.tight_layout(w_pad=5.5)

Here we use tight_layout() method with w_pad parameter.

Read Matplotlib 3D scatter

Matplotlib tight_layout rect

We’ll learn how to specify a rectangle in normalized figure coordinates into which the whole subplots area including labels will fit.

The following is the syntax:

matplotlib.pyplot.tight_layout(rect=(0, 0, 1, 1)

Let’s see an example:

# Import Library

import numpy as np 
import matplotlib.pyplot as plt 
 
# Create figure and subplot

fig, ax = plt.subplots(1, 2) 

# Define  Data

x = np.arange(0.0, 30.0 , 0.02) 
y1 = np.sin(x) 
y2 = np.exp(-x) 

# PLot Subplot 1

ax[0].plot(x, y1, label='Line1') 
ax[0].plot(x, y2, marker ='o', label='Line2') 

# Add legend

ax[0].legend(loc='upper left')

# Define Data

y3 = np.tan(x) 
y4 = np.exp(-2 * x) 

# Plot subplot 2

ax[1].plot(x, y3, color ='cyan', label='Line3') 
ax[1].plot(x, y4, color ='tab:red', marker ='o', label='Line4') 

# Add legend

ax[1].legend(loc='upper right')

# tight_layout

fig.tight_layout(rect=(1.5, 0.86, 4.23, 2.55)) 

# Show

plt.show() 
  • In the example, we use the arange(), sin(), cos(), tan(), exp() functions to define data.
  • To plot a graph, use the plt.plot() method.
  • To place the legend for each subplot we add labels and to activate labels for each curve, we use the legend() method.
  • tight_layout() method with rect parameter is used. We pass a tuple having values 1.5, 0.86, 4.23, 2.55.
matplotlib tight_layout rect
Simple Plot Without tight_layout()
matplotlib tight_layout with rect
tight_layout()

Read Stacked Bar Chart Matplotlib

Matplotlib tight_layout savefig

Sometimes, we get large borders on created figures. To get borders of auto fit size we use the tight_layout() function.

Example:

# Import Library

import numpy as np 
import matplotlib.pyplot as plt 
 
# Define  Data

x = np.arange(0.0, 30.0 , 0.02) 
y1 = np.sin(x) 
y2 = np.exp(-x) 

# Plot

plt.plot(x, y1, label='Line1') 
plt.plot(x, y2, marker ='o', label='Line2') 

# tight_layout

plt.tight_layout()

# Savefig

plt.savefig('SimplePlot.png')

# Show

plt.show() 
  • In the above example, we use the tight_layout() method to adjust the borders of the plot.
  • plt.savefig() method is used to save the figure as png.
matplotlib tight_layout savefig
savefig()

The above output comes when we save the plot without using the tight_layout function. Here we get extra borders.

matplotlib savefig with tight_layout
savefig() with tight_layout()

Read Matplotlib two y axes

Matplotlib tight_layout subplots

The tight_layout function in the matplotlib library is used to automatically adjust the proper space between the subplots so that it fits into the figure area without cutting.

Let’s see an example:

# Importing library

import numpy as np
import matplotlib.pyplot as plt

# Create figure and subplots

fig, ax = plt.subplots(3,1)

# Define Data

x1= [2,4,6]
y1= [3,6,9]

x2= [5,10,15]
y2= [6,12,18]

x3= [2,4,6]
y3= [3,6,9]

# Plot lines

ax[0].plot(x1, y1)
ax[1].plot(x2, y2)
ax[2].plot(x3, y3)

# Add title

ax[0].set_title("Graph 1 ")
ax[1].set_title("Graph 2")
ax[2].set_title("Graph 3")

# Auto adjust

plt.tight_layout()

# Display

plt.show()
  • In the above example, we create figures and subplots with 3 rows and 1 column.
  • After this, we define data coordinates and plot a line between them using the plot() method.
  • set_title() method is used to add title.
  • To remove the overlapping or to adjust the subplots automatically we use the tight_layout() method.
matplotlib tight_layout subplots
“Plot Without tight_layout() method”
matplotlib tight_layout with subplots
“Subplots with tight_layout() function”

Also read, Horizontal line matplotlib

Matplotlib tight_layout suptitle

Sometimes, the suptitle and title of the plot overlap each other and the plot looks untidy. We’ll learn how to adjust automatically the suptitle of the plot.

Example:

# Import Library

import numpy as np
import matplotlib.pyplot as plt

# Create figure

fig = plt.figure()

# Define Data

x = np.random.randint(10,size=500)
y = np.random.random(500)

# Add sup tile

fig.suptitle('SUPTITLE', fontsize=24)

# Create subplot 1

plt.subplot(121)

# Plot line

plt.plot(x)

# Add Title

plt.title('RANDINT PLOT', fontsize=15)

# Create subplot 2

plt.subplot(122)

# Plot line

plt.plot(y)

# Add Title

plt.title('RANDOM PLOT', fontsize=15)

# Auto adjust

plt.tight_layout()

# Dispaly

plt.show()
  • In the above example, we import matplotlib.pyplot and numpy module.
  • Next, we create a figure using plt.figure() method.
  • After that, we define data using randint() and random() methods.
  • Then we add a title to the figure, by using the fig.suptitle() method.
  • plt.subplots() method is used to create subplots in a figure area.
  • To plot the line between data coordinates, use the plt.plot() method.
  • To add a title to the plot, use the plt.title() method.
  • To remove the overlapping of titles, use the tight_layout() function.
matplotlib tight_layout suptile
“Overlap title plot”
matpltlib suptile with tight_layout
tight_layout()

Read Draw vertical line matplotlib

Matplotlib tight_layout cuts labels

Sometimes, the x-axis label and y-axis label of the plot overlap each other and the plot looks untidy. We’ll learn how to automatically adjust the labels of the plot.

Let’s see an example:

# Importing library

import numpy as np
import matplotlib.pyplot as plt

# Create figure and subplots

fig, ax = plt.subplots(2,2, figsize=(8, 5))

# Define Data

x1= np.random.randint(10,size=500)

x2= [5,10,15]
y2= [6,12,18]

x3= np.arange(0.0, 30.0 , 0.02) 
y3= np.tan(x3)

x4 = np.arange(0.0, 30.0 , 0.02) 
y4 = np.sin(x4)

# Plot lines

ax[0, 0].plot(x1)
ax[0, 1].plot(x2, y2)
ax[1, 0].plot(x3, y3)
ax[1, 1].plot(x4, y4)

# Add xlabel

ax[0, 0].set_xlabel('X-Axis')
ax[1, 0].set_xlabel('X-Axis')
ax[0, 1].set_xlabel('X-Axis')
ax[1, 1].set_xlabel('X-Axis')

# Add ylabel

ax[0, 0].set_ylabel('Y-Axis')
ax[1, 0].set_ylabel('Y-Axis')
ax[0, 1].set_ylabel('Y-Axis')
ax[1, 1].set_ylabel('Y-Axis')

# Auto adjust

plt.tight_layout()

# Display

plt.show()
  • In the above example, we import matplotlib.pyplot and numpy library.
  • After this, we create figures and subplots by using the subplots() method.
  • Then we define data coordinates and plot a line between them, using the plt.plot() method.
  • set_xlabel() and set_ylabel() methods are use to add labels at x-axis and y-axis respectively.
  • To automatically adjust the plot, use the tight_layout() function.
matplotlib tight_layout cuts labels
“Overlap labels”
matplotlib cuts labels with tight_layout
tight_layout()

Check out, Matplotlib invert y axis

Matplotlib tight_layout legend

Sometimes, when we save a plot with a legend in our machine we find that the legend cut-offs. So, we’ll learn how to solve the problem of legend cut off while saving a plot.

To avoid the cutoff of legend, use the tight_layout() method of pyplot module of matplotlib.

Let’s see an example:

# Import Library

import matplotlib.pyplot as plt

# Create figure

fig = plt.figure(1)

# Plot

plt.plot([1, 2, 3, 4, 5], [1, 0, 1, 0, 1], label='A label')
plt.plot([1, 2, 3, 8, 2.5], [1, 2, 2, 1, 0], label='B label')

# Legend

plt.legend(loc='center left', bbox_to_anchor=(1, 0))

# Savefig

#fig.savefig('Cut-off Legend.png')

# Display

plt.show()
  • Here we import matplotlib.pyplot library and create figure by using plt.figure().
  • After this, we plot a chart and define labels.
  • Then we use plt.legend() method to add a legend in the plot. And we pass loc and bbox_to_anchor parameters and set their value center left, and 1, 0 respectively.
  • To save a plot in your machine, use savefig() method.
matplotlib tight_layout legend
” Jupyter Notebook Output “
matplotlib tight_layout with legend
” Savefig Output “

In the above output, we see that when we save the plot in our machine by using the savefig() method the legends get cut off.

To overcome this problem we use the tight_layout() method.

Example:

# Import Library

import matplotlib.pyplot as plt

# Create figure

fig = plt.figure(1)

# Plot

plt.plot([1, 2, 3, 4, 5], [1, 0, 1, 0, 1], label='A label')
plt.plot([1, 2, 3, 8, 2.5], [1, 2, 2, 1, 0], label='B label')

# Legend

plt.legend(loc='center left', bbox_to_anchor=(1, 0))

# Adjust legend

plt.tight_layout()

# Savefig

fig.savefig('Proper Legend.png')

# Display

plt.show()

Now, here we use plt.tight_layout() method, which is used for auto adjustment of plot, ticklabels, labels, and legends.

matplotlib legend with tight_layout
plt.tight_layout()

In the above output, we use the tight_layput() method to get the proper legend.

Read Put legend outside plot matplotlib

Matplotlibb tight_layout bbox

In this section, we’ll learn how to avoid overlapping, cut-offs, and extra space while we save plots in our system. bbox_inches parameter of savefig() method and tight_layout() method of matplotlib helps you to overcome this problem.

Let’s see an example:

# Importing library

import numpy as np
import matplotlib.pyplot as plt

# Create figure and subplots

fig, ax = plt.subplots(2,1, figsize=(8, 5))

# Define Data

x1= np.random.randint(10,size=500)

x2= np.arange(0.0, 30.0 , 0.02) 
y2= np.tan(x2)

# Plot lines

ax[0].plot(x1)
ax[1].plot(x2, y2)

# Add sup tile

fig.suptitle('SUPTITLE', fontsize=24)

# Add xlabel

ax[0].set_xlabel('X-Axis')
ax[1].set_xlabel('X-Axis')

# Add ylabel

ax[0].set_ylabel('Y-Axis')
ax[1].set_ylabel('Y-Axis')

# Auto adjust

plt.tight_layout()
fig.savefig('tight_layout bbox.png', bbox_inches='tight')

# Display

plt.show()
  • In the above example, to define data coordinates, we use randint(), arange(), and tan() methods.
  • After this, to create plot curves, we use the plot() method.
  • suptitle() method is used to add a title to the plot.
  • set_xlabel() and set_yalbel() method is used to add labels at x and y axes respectively.
  • plt.tight_layout() method is to automatically adjust the subplot.
  • We pass the bbox_inches argument to savefig() method and set its value to “tight”, as it removes its extra border.
matplotlib tight_layout bbox
Overlapped Plot
matplotlib tight_layout with bbox
plt.tight_layout() and bbox_inches =’tight’

Check out, Matplotlib save as pdf + 13 examples

Matplotlib tight_layout not applied

In some cases, the tight_layout() method does not work properly. In section, we’ll learn what we have to do in such cases.

Let’s understand the whole concept with the help of an example:

# Import Library

import matplotlib.pyplot as plt

# Create figure

fig = plt.figure(1)

# Define Data

data = np.arange(0.0, 30.0 , 0.02) 
x1 = np.sin(data)
x2 = np.cos(data)

# Plot

plt.plot(data, x1, label='Sin')
plt.plot(data, x2, label='Cos')

# Add legend

plt.legend(loc='center left', bbox_to_anchor=(0.8,-0.1))

# tight_layout

plt.tight_layout()

# display

plt.show()
matplotlib tight_layout not applied

From the above example, we conclude that the tight_layout() method doesn’t work as the legend is overlapping with ticklabels.

Solution: Use tight_layout() with rect parameter.

Code:

# Import Library

import matplotlib.pyplot as plt

import numpy as np

# Create figure

fig = plt.figure(1)

# Define Data

data = np.arange(0.0, 30.0 , 0.02) 
x1 = np.sin(data)
x2 = np.cos(data)

# Plot

plt.plot(data, x1, label='Sin')
plt.plot(data, x2, label='Cos')

# Add legend

plt.legend(loc='center left', bbox_to_anchor=(0.8,-0.1))

# tight_layout with rect

plt.tight_layout(rect=(1.5, 0.86, 3.23, 2.55))

# display

plt.show()
  • In the above example, we import matplotlib.pyplot library and create a figure using plt.figure().
  • After this, we define data using arange(), sin(), and cos() methods of numpy.
  • To plot the data, use the plot() method of the matplotlib pyplot module.
  • To place the legend we add label and to activate the label for each curve, we use the legend() method.
  • To properly fit the subplot area including labels, we use the tight_layout method with the rect parameter.
matplotlib tight_layout not working
plt.tight_layout(rect=())

Read What is matplotlib inline

Matplotlib tight_layout rcparams

The matplotlib.pyplot.tight_layout() method only adjusts the subplot automatically when it is called. If you want each time the figure is redrawn, this change must be made, set rcParams.

The syntax is following:

rcParams["figure.autolayout]

By default, its value is False. Set it to True.

Let’s see an example:

# Importing library

import numpy as np
import matplotlib.pyplot as plt

# Default adjustment

plt.rcParams["figure.autolayout"] = True

# Create figure and subplots

fig, ax = plt.subplots(2,1, figsize=(8, 5))

# Define Data

x1= [0, 1, 2, 3, 4]
y1= [2.5, 3.5, 4.5, 6.3, 2.1]

x2= [2, 4, 8, 3, 1]
y2= [5.2, 6, 1, 2.6, 9]

# Plot lines

ax[0].plot(x1, y1)
ax[1].plot(x2, y2)

# Add sup tile

fig.suptitle('SUPTITLE', fontsize=24)

# Add xlabel

ax[0].set_xlabel('X-Axis')
ax[1].set_xlabel('X-Axis')

# Add ylabel

ax[0].set_ylabel('Y-Axis')
ax[1].set_ylabel('Y-Axis')

# Display

plt.show()

In the above example, we use rcParams[“figure.autolayout”] instead of tight_layout() method to adjust the subplots and set it to value True.

matplotlib tight_layout rcparams
plt.rcParams[“figure.autolayout”]

Example:

# Import Library

import numpy as np
import matplotlib.pyplot as plt

# Create figure

fig = plt.figure()

# Define Data

x = np.random.randint(10,size=500)
y = np.random.random(500)

# Add sup tile

fig.suptitle('SUPTITLE', fontsize=24)

# Create subplot 1

plt.subplot(121)

# Plot line

plt.plot(x)

# Add Title

plt.title('RANDINT PLOT', fontsize=15)

# Create subplot 2

plt.subplot(122)

# Plot line

plt.plot(y)

# Add Title

plt.title('RANDOM PLOT', fontsize=15)

# Dispaly

plt.show()
matplotlib rcParams tight_layout

Now, see in the above example, we do not use any method for adjustment of subplots. It automatically, adjust the subplots because we use rcParams[] in the previous example. So, each time figure is redrawn, it adjusts automatically.

Read Python plot multiple lines using Matplotlib

Matplotlib imshow tight_layout

We’ll learn how we can use the tight_layout method with imshow() method. Firstly we understand what imshow() function is.

imshow() function is used to display data as an image.

The tick_layout method is used with imshow() method to automatically adjust the plot.

Example:

# Import Library

import numpy as np
import matplotlib.pyplot as plt

# Create figure and subplot

fig = plt.figure(figsize=(8,5))
ax = plt.subplot(111)

# Define Data

arr = np.arange(100).reshape((10,10))

# Title

fig.suptitle('imshow() function Example', fontweight ="bold", fontsize= 24)

# plot

im = ax.imshow(arr, interpolation="none")

# adjsut 

plt.tight_layout()

# Visualize

plt.show()
  • In the above example, we import matplotlib.pyplot and numpy library.
  • After this, we create and subplot by using figure() and subplot() method respectively,
  • Then we define data using arange() method and reshape it by using reshape() method.
  • To add a suptitle to the figure, we use suptitle() method. And we pass fontsize, and fontweight as a parameter.
  • Then we use imshow() method to plot a graph and tight_layout() method for auto adjustment of the plot.
matplotlib imshow tight layout
imshow()

Read Matplotlib plot a line

Matplotlib tight_layout gridspec

We’ll learn how to use the tight_layout() method with GridSpec class. Firstly understand what does GridSpec class is.

The matplotlib.grispec.GridSpec class is used to specify the geometry of the grid to place a subplot. The number of rows and columns must be set.

The syntax of GridSpec class is as follow:

matplotlib.gridspec.GridSpec(nrows, ncols, figure=None, left=None, bottom=None, right=None, top=None, wspace=None, hspace=None, width_ratio=None, height_ratio=None)

GridSpec has its own tight_light() method. The tight_layout() method of pyplot also works with it. We can also use the rect parameter which specifies the bounding box. The h_pad and w_pad parameter is used to adjust the top and bottom of the plot.

Let’s see an example:

# Import Library

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

# Create figure

fig = plt.figure(figsize =([9, 5]))

# GridSpec

gs = gridspec.GridSpec(2, 6)

# Subplots

ax1 = plt.subplot(gs[0, :2])
ax1.set_ylabel('ylabel', labelpad = 0, fontsize = 12)
ax1.plot([0, 1, 2], [2, 3.6, 4])
 
ax2 = plt.subplot(gs[0, 2:4])
ax2.set_ylabel('ylabel', labelpad = 0, fontsize = 12)
ax2.plot([2, 5.5, 9], [2, 3.6, 4])
 
ax3 = plt.subplot(gs[1, 1:3])
ax3.set_ylabel('ylabel', labelpad = 0, fontsize = 12)
ax3.plot([0, 1, 2], [1, 2, 3])
 
ax4 = plt.subplot(gs[1, 3:5])
ax4.set_ylabel('ylabel', labelpad = 0, fontsize = 12)
ax4.plot([2.3, 4.6, 8.8, 9.6], [4.2, 5.5, 6, 4])

# Auto adjust

plt.tight_layout()

# Display

plt.show()
  • In the above example, we pyplot and GridSpec class of matplotlib.
  • To create a figure, we use figure() method.
  • After this we use GridSpec() method to create grid to place subplot.
  • To set labels at y-axis, we use set_yalbel() method.
  • Then we use the tight_layout() method to automatically adjust the subplots.
matplotlib tight_layout GridSpec
Overlapped Subplots
matplotlib tight_layout with GridSpec
tight_layout()

Read Matplotlib rotate tick labels

Matplotlib tight_layout colorbar

We’ll learn how to use tight_layout() method with colorbar() method. A colorbar() method is used to add a color bar to the plot.

The syntax of colorbar() method is as below:

matplotlib.pyplot.colorbar(mappable=None, cax=None, ax=None, **kw)

Example:

# Import Library

import numpy as np
import matplotlib.pyplot as plt

# Create figure and subplot

fig = plt.figure(figsize=(8,5))
ax = plt.subplot(111)

# Define Data

arr = np.arange(100).reshape((10,10))

# Plot

im = ax.imshow(arr, interpolation="none")

# Add colorabar

plt.colorbar(im)

# adjsut 

plt.tight_layout()

# Visualize

plt.show()
  • Here we define data using arange() method of numpy and then we reshape the the plot by using reshape() method.
  • After this, we plot graph using imshow() method.
  • To add colorbar to the plot, use colorbar() method.
  • tight_layout() method is used to automatically adjust the plot.
matplotlib tight_layout colorbar
plt.colorbar()

Read Matplotlib change background color

Matplotlib table tight_layout

We’ll learn how we can auto-adjust the plot and table within a figure area without overlapping. In matplotlib by using matplotlib.pyplot.table() method we can create a table.

The syntax to create a table is as follow:

matplotlib.pyplot.table(cellText=None, cellColours=None, 
                        cellLoc=’right’,colWidths=None,
                        rowLabels=None, rowColours=None, 
                        rowLoc=’left’,colLabels=None, 
                        colColours=None, colLoc=’center’, 
                        loc=’bottom’, bbox=None, 
                        edges=’closed’, **kwargs) 

Let’s see an example:

# Import Library

import numpy as np
import matplotlib.pyplot as plt

# Define data

data = np.random.rand(3, 2)
columns = ('Col1', 'Col2')
rows = ['# %d' % p for p in (1, 2, 3)] 

# Plot data

plt.plot(data)

# X-axis 

plt.xlabel('X-axis')

# Define table


the_table = plt.table(cellText=data,rowLabels=rows, colLabels=columns,loc='bottom', bbox=[0,-0.55,1,.33])

# auto adjust

plt.tight_layout()

# Display

plt.show()
  • Here we import numpy and matplotlib.pyplot library.
  • Next, we define data using random.rand() method and we also define columns and rows.
  • By using plt.plot() we create a graph and to define its x-axis label we use plt.xlabel() method.
  • To generate a table, use the table() method of matplotlib with cellText, rowLabels, colLabels, loc, and bbox argument.
  • To avoid overlapping and to make a tidy plot we use the tight_layout() method.
matplotlib table tight_layout
plt.tight_layout()

Check out, Matplotlib scatter marker

Matplotlib scatter tight_layout

Here we’ll learn how to use the tight_layout() method within scatter plot.

Example:

# Import Library

import matplotlib.pyplot as plt

# Create figure

fig = plt.figure(1)

# Define Data

x =  [1, 2, 3, 4, 5]
y1 = [5, 10, 15, 20, 25]
y2 = [10, 20, 30, 40, 50]

# Plot

plt.scatter(x, y1, label='X*5')
plt.scatter(x, y2, label='X*10')

# Add legend

plt.legend(loc='center left', bbox_to_anchor=(0.8,-0.1))

# tight_layout with rect

plt.tight_layout(rect=(1.5, 0.86, 3.23, 2.55))

# display

plt.show()
  • Here we plot scatter graph using the scatter() method. And to add a legend to the plot, we use plt.legend() method.
  • We see that without using the tight_layout() method the legend and x-axis ticklabels of the scatter plots overlap each other. So, to avoid overlapping we use the tight_layout() method with rect parameter.
matplotlib scatter tight_layout
“Overlapped Scatter Plot”
matplotlib scatter with tight_layout
plt.tight_layout()

Read Matplotlib dashed line

Matplotlib 3d plot tight layout

We’ll learn how we can auto-adjust the 3d plot using the tight_layout() method.

Example:

# Importing Libraries

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d

# Create 1st subplot

fig = plt.figure(figsize=(10, 6))
ax = fig.add_subplot(1, 2, 1, projection='3d')

# Define Data

x1= [0.2, 0.4, 0.6, 0.8, 1]
y1= [0.3, 0.6, 0.8, 0.9, 1.5]
z1= [2, 6, 7, 9, 10]

# Plot graph

ax.scatter3D(x1, y1, z1, color='m')
ax.set_xlabel('X-Axis')
ax.set_ylabel('Y-Axis')
ax.set_zlabel('Z-Axis')

# Create 2nd subplot

ax = fig.add_subplot(1, 2, 2, projection='3d')

# Define Data

x2 = np.arange(0, 20, 0.2)
y2 = np.sin(x2)
z2 = np.cos(x2)

# Plot graph

ax.scatter3D(x2, y2, z2, color='r')
ax.set_xlabel('X-Axis')
ax.set_ylabel('Y-Axis')
ax.set_zlabel('Z-Axis')

# auto adjust


plt.tight_layout()

# Display graph

plt.show()
  • In the above example we import matplotlib.pyplot, numpy, and mplot3d libraries.
  • By using add_subplot() method we create 1st subplot and then we define data used to for plotting.
  • ax.scatter3D() method is used to create 3D scatter plot.
  • After this, again we use add_subplot() method to create 2nd subplot and then we define data which is used for plotting.
  • Again, we use ax.scatter3D() method to plot another 3D scatter graph.
  • To auto adjsut the plot layout we use tight_layout().
matplotlib 3d plot tight layout
tight_layout()

Read Matplotlib plot_date

Matplotlib undo tight_layout

Sometimes, by default, the auto-adjustment feature is turned on, in order to perform the adjustment each time the figure is redrawn. If you want to turn it off, you can call the fig.set_tight_layout() method and pass the False bool value to the method.

Let’s see an example

# Import Library

import numpy as np 
import matplotlib.pyplot as plt 

# Create figure and subplot

fig, ax = plt.subplots(1, 2) 

# Define  Data

x = np.arange(0.0, 30.0 , 0.02) 
y1 = np.sin(x) 
y2 = np.exp(-x) 

# PLot Subplot 1

ax[0].plot(x, y1, label='Line1') 
ax[0].plot(x, y2, marker ='o', label='Line2') 

# Add legend

ax[0].legend(loc='upper left')

# Define Data

y3 = np.tan(x) 
y4 = np.exp(-2 * x) 

# plot subplot 2

ax[1].plot(x, y3, color ='cyan', label='Line3') 
ax[1].plot(x, y4, color ='tab:red', marker ='o', label='Line4') 

# Add legend

ax[1].legend(loc='upper right')

# Show

plt.show() 
  • In the above example, we create figures and subplots by using the subplots() method of matplotlib.pyplot.
  • After this, we define data using arange(), sin, and exp() method.
  • Then to plot a graph we use the plot() method and we also define legend by using the legend() function.
matplotlib undo tight_layout
“Auto Adjusted Plot”

From the above-generated output, we conclude that the generated subplots are auto-adjusted by default.

Code: Undo or Turn Off tight_layout()

# Import Library


import numpy as np 
import matplotlib.pyplot as plt 

# Create figure and subplot


fig, ax = plt.subplots(1, 2) 

# undo tight_layout

fig.set_tight_layout(False)

# Define  Data

x = np.arange(0.0, 30.0 , 0.02) 
y1 = np.sin(x) 
y2 = np.exp(-x) 

# PLot Subplot 1


ax[0].plot(x, y1, label='Line1') 
ax[0].plot(x, y2, marker ='o', label='Line2') 

# Add legend

ax[0].legend(loc='upper left')

# Define Data


y3 = np.tan(x) 
y4 = np.exp(-2 * x) 

# plot subplot 2


ax[1].plot(x, y3, color ='cyan', label='Line3') 
ax[1].plot(x, y4, color ='tab:red', marker ='o', label='Line4') 

# Add legend

ax[1].legend(loc='upper right')

# Show

plt.show() 

Now the by using the above code, we can undo the auto adjustment of the subplots. Here we call the fig.set_tight_layout() method with False value and undo the auto-layout feature of the plot.

matplotlib turn off tight layout
fig.set_tight_layout(False)

Read Matplotlib log log plot

Matplotlib tight_layout alternative

An alternative to tight_layout is constrained_layout

We use the constrained_layout to fit plots clearly within your figure. constrained_layout automatically adjusts subplots, legends, colorbars, titles, and labels so that they fit in the figure area while still preserving the layout requested by the user.

Before adding any axes to a figure constrained_layout must be activated. In two ways we can activate it.

  • Activate via rcParams:
matplotlib.pyplot.rcParams['figure.constrained_layout.use']=True
  • Activate via argument to subplots() or figure() methods:
# Using subplots()

plt.subplots(constrained_layout=True)

# Uisng figure()

plt.figure(constrained_layout=True)

Let’s see a simple example first to understand more clearly:

# Importing library

import numpy as np
import matplotlib.pyplot as plt

# Create figure and subplots


fig, ax = plt.subplots(2,2, figsize=(8, 5))

# Define Data

x1= np.random.randint(10,size=500)

x2= np.linspace(100, 200, num=10)
y2= np.cos(x2)

x3= np.arange(0.0, 30.0 , 0.02) 
y3= np.tan(x3)

x4 = np.arange(0.0, 30.0 , 0.02) 
y4 = np.sin(x4)

# Plot lines

ax[0, 0].plot(x1)
ax[0, 1].plot(x2, y2)
ax[1, 0].plot(x3, y3)
ax[1, 1].plot(x4, y4)

# Add xlabel

ax[0, 0].set_xlabel('X-Axis')
ax[1, 0].set_xlabel('X-Axis')
ax[0, 1].set_xlabel('X-Axis')
ax[1, 1].set_xlabel('X-Axis')

# Add ylabel

ax[0, 0].set_ylabel('Y-Axis')
ax[1, 0].set_ylabel('Y-Axis')
ax[0, 1].set_ylabel('Y-Axis')
ax[1, 1].set_ylabel('Y-Axis')

# Display

plt.show()
matplotlib tight layout alternative
  • In the above example, the axis labels or titles or ticklabels overlap each other and make the plot untidy. To prevent this, the location of axes needs to be adjusted.
  • For subplots, this can be done manually by adjusting the parameters using Figure.subplots_adjust or we will do the adjustment automatically by specifying constrained_layout=True.

Code: For auto adjustment

# Importing library

import numpy as np
import matplotlib.pyplot as plt

# Create figure and subplots

fig, ax = plt.subplots(2,2, figsize=(8, 5), constrained_layout=True)

# Define Data

x1= np.random.randint(10,size=500)

x2= np.linspace(100, 200, num=10)
y2= np.cos(x2)

x3= np.arange(0.0, 30.0 , 0.02) 
y3= np.tan(x3)

x4 = np.arange(0.0, 30.0 , 0.02) 
y4 = np.sin(x4)

# Plot lines

ax[0, 0].plot(x1)
ax[0, 1].plot(x2, y2)
ax[1, 0].plot(x3, y3)
ax[1, 1].plot(x4, y4)

# Add xlabel

ax[0, 0].set_xlabel('X-Axis')
ax[1, 0].set_xlabel('X-Axis')
ax[0, 1].set_xlabel('X-Axis')
ax[1, 1].set_xlabel('X-Axis')

# Add ylabel

ax[0, 0].set_ylabel('Y-Axis')
ax[1, 0].set_ylabel('Y-Axis')
ax[0, 1].set_ylabel('Y-Axis')
ax[1, 1].set_ylabel('Y-Axis')

# Display

plt.show()
matplotlib alternative of tight_layout
constrained_layout=True

Read Matplotlib subplots_adjust

Matplotlib constrained_layout vs tight_layout

We’ll discuss constrained_layout vs tight_layout.

constrained_layouttight_layout
It preserves the logical layout requested by the user.It may not preserve the logical layout requested by the user.
constrained_layout uses a constraint solver to determine the size of the axes.tight_layout does not use a constraint solver to determine the size of the axes.
constrained_layout needs to be activated before any axes are added.tight_layout doesn’t need to be activated before axes are added.
Activate via rcParams:
plt.rcParams[‘figure.constrained_layout.use’]=True
Activate via rcParams:
plt.rcParams[‘figure.autolayout’]=True
Activate via methods:
plt.subplots(constrained_layout=True)
Activate via methods:
plt.tight_layout()
constrained_layout vs tight_layout

Let’s see an example:

Example: tight_layout

# Import Library


from matplotlib.figure import Figure

# Create figure


fg = Figure()

# Create subplot


ax = fg.subplots(5, 1)

# Plot


for i in range(5):
    ax[i].plot(range(25+25*i))

# Add title


fg.suptitle('lots of lines')

# tight_layout

fig.tight_layout()

# Save image


fg.savefig("tight_layout.png")
matplotlib constrained_layout vs tight_layout
tight_layout

Example: constrained_layout

# Import Library

from matplotlib.figure import Figure

# Create figure


fg = Figure(constrained_layout=True)

# Create subplot

ax = fg.subplots(5, 1)

# Plot

for i in range(5):
    ax[i].plot(range(25+25*i))

# Add title

fg.suptitle('lots of lines')

# Save image

fg.savefig("constrained_layout.png")
matplotlib tight_layout vs constrained_layout
constrained_layout

From the above examples, we see that tight_layout does not work better. To make figures with subplots and ticklabels work better, use constrained_layout.

You may also like:

So, in this Python tutorial, we have discussed the “Matplotlib tight_layout” and we have also covered some examples related to it. These are the following topics that we have discussed in this tutorial.

  • Matplotlib tick_layout
  • Matplotlib tight_layout example
  • Matplotlib tight_layout pad
  • Matplotlib tight_layout hspace
  • Matplotlib tight_layout wspace
  • Matplotlib tight_layout rect
  • Matplotlib tight_layout savefig
  • Matplotlib tight_layout subplots
  • Matplotlib tight_layout suptitle
  • Matplotlib tight_layout cuts labels
  • Matplotlib tight_layout legend
  • Matplotlib tight_layout bbox
  • Matplotlib tight_layout not applied
  • Matplotlib tight_layout rcparams
  • Matplotlib imshow tight_layout
  • Matplotlib tight_layout gridspec
  • Matplotlib tight_layout colorbar
  • Matplotlib table tight_layout
  • Matplotlib scatter tight_layout
  • Matplotlib 3d plot tight layout
  • Matplotlib undo tight_layout
  • Matplotlib tight_layout alternative
  • Matplotlib constrained_layout vs tight_layout