17 авг. 2022 г.
читать 2 мин
Часто вы можете использовать подзаголовки для отображения нескольких графиков рядом друг с другом в Matplotlib. К сожалению, эти подсюжеты имеют тенденцию перекрывать друг друга по умолчанию.
Самый простой способ решить эту проблему — использовать функцию Matplotlibtight_layout ().В этом руководстве объясняется, как использовать эту функцию на практике.
Создать подсюжеты
Рассмотрим следующее расположение 4 подзаголовков в 2 столбцах и 2 строках:
import matplotlib.pyplot as plt
#define subplots
fig, ax = plt.subplots(2, 2)
#display subplots
plt.show()
Обратите внимание, как сюжеты немного перекрывают друг друга.
Отрегулируйте интервал между подграфиками, используя tight_layout()
Самый простой способ решить эту проблему перекрытия — использовать функцию Matplotlibtight_layout () :
import matplotlib.pyplot as plt
#define subplots
fig, ax = plt.subplots(2, 2)
fig. tight_layout ()
#display subplots
plt.show()
Отрегулируйте интервал заголовков подзаголовков
В некоторых случаях у вас также могут быть названия для каждого из ваших сюжетов. К сожалению, даже функция tight_layout() приводит к перекрытию заголовков подзаголовков:
import matplotlib.pyplot as plt
#define subplots
fig, ax = plt.subplots(2, 2)
fig. tight_layout ()
#define subplot titles
ax[0, 0].set_title('First Subplot')
ax[0, 1].set_title('Second Subplot')
ax[1, 0].set_title('Third Subplot')
ax[1, 1].set_title('Fourth Subplot')
#display subplots
plt.show()
Способ решить эту проблему — увеличить отступ по высоте между подграфиками с помощью аргумента h_pad :
import matplotlib.pyplot as plt
#define subplots
fig, ax = plt.subplots(2, 2)
fig. tight_layout (h_pad= 2 )
#define subplot titles
ax[0, 0].set_title('First Subplot')
ax[0, 1].set_title('Second Subplot')
ax[1, 0].set_title('Third Subplot')
ax[1, 1].set_title('Fourth Subplot')
#display subplots
plt.show()
Отрегулируйте интервал общего заголовка
Если у вас есть общий заголовок, вы можете использовать функцию subplots_adjust() , чтобы убедиться, что он не перекрывается с заголовками подзаголовков:
import matplotlib.pyplot as plt
#define subplots
fig, ax = plt.subplots(2, 2)
fig. tight_layout (h_pad= 2 )
#define subplot titles
ax[0, 0].set_title('First Subplot')
ax[0, 1].set_title('Second Subplot')
ax[1, 0].set_title('Third Subplot')
ax[1, 1].set_title('Fourth Subplot')
#add overall title and adjust it so that it doesn't overlap with subplot titles
fig.suptitle('Overall Title')
plt.subplots_adjust(top= 0.85 )
#display subplots
plt.show()
Вы можете найти больше руководств по Matplotlib здесь .
I need to generate a whole bunch of vertically-stacked plots in matplotlib. The result will be saved using savefig
and viewed on a webpage, so I don’t care how tall the final image is, as long as the subplots are spaced so they don’t overlap.
No matter how big I allow the figure to be, the subplots always seem to overlap.
My code currently looks like
import matplotlib.pyplot as plt
import my_other_module
titles, x_lists, y_lists = my_other_module.get_data()
fig = plt.figure(figsize=(10,60))
for i, y_list in enumerate(y_lists):
plt.subplot(len(titles), 1, i)
plt.xlabel("Some X label")
plt.ylabel("Some Y label")
plt.title(titles[i])
plt.plot(x_lists[i],y_list)
fig.savefig('out.png', dpi=100)
asked Jun 30, 2011 at 21:09
1
You can use plt.subplots_adjust
to change the spacing between the subplots.
call signature:
subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)
The parameter meanings (and suggested defaults) are:
left = 0.125 # the left side of the subplots of the figure
right = 0.9 # the right side of the subplots of the figure
bottom = 0.1 # the bottom of the subplots of the figure
top = 0.9 # the top of the subplots of the figure
wspace = 0.2 # the amount of width reserved for blank space between subplots
hspace = 0.2 # the amount of height reserved for white space between subplots
The actual defaults are controlled by the rc file
answered Jun 30, 2011 at 21:45
CyanRookCyanRook
8,2144 gold badges20 silver badges18 bronze badges
0
Using subplots_adjust(hspace=0)
or a very small number (hspace=0.001
) will completely remove the whitespace between the subplots, whereas hspace=None
does not.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as tic
fig = plt.figure(figsize=(8, 8))
x = np.arange(100)
y = 3.*np.sin(x*2.*np.pi/100.)
for i in range(1, 6):
temp = 510 + i
ax = plt.subplot(temp)
plt.plot(x, y)
plt.subplots_adjust(hspace=0)
temp = tic.MaxNLocator(3)
ax.yaxis.set_major_locator(temp)
ax.set_xticklabels(())
ax.title.set_visible(False)
plt.show()
hspace=0
or hspace=0.001
hspace=None
answered Mar 22, 2012 at 17:43
Alexa HalfordAlexa Halford
1,1132 gold badges12 silver badges13 bronze badges
0
Similar to tight_layout
matplotlib now (as of version 2.2) provides constrained_layout
. In contrast to tight_layout
, which may be called any time in the code for a single optimized layout, constrained_layout
is a property, which may be active and will optimze the layout before every drawing step.
Hence it needs to be activated before or during subplot creation, such as figure(constrained_layout=True)
or subplots(constrained_layout=True)
.
Example:
import matplotlib.pyplot as plt
fig, axes = plt.subplots(4,4, constrained_layout=True)
plt.show()
constrained_layout may as well be set via rcParams
plt.rcParams['figure.constrained_layout.use'] = True
See the what’s new entry and the Constrained Layout Guide
answered Aug 2, 2018 at 15:25
0
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(10,60))
plt.subplots_adjust( ... )
The plt.subplots_adjust method:
def subplots_adjust(*args, **kwargs):
"""
call signature::
subplots_adjust(left=None, bottom=None, right=None, top=None,
wspace=None, hspace=None)
Tune the subplot layout via the
:class:`matplotlib.figure.SubplotParams` mechanism. The parameter
meanings (and suggested defaults) are::
left = 0.125 # the left side of the subplots of the figure
right = 0.9 # the right side of the subplots of the figure
bottom = 0.1 # the bottom of the subplots of the figure
top = 0.9 # the top of the subplots of the figure
wspace = 0.2 # the amount of width reserved for blank space between subplots
hspace = 0.2 # the amount of height reserved for white space between subplots
The actual defaults are controlled by the rc file
"""
fig = gcf()
fig.subplots_adjust(*args, **kwargs)
draw_if_interactive()
or
fig = plt.figure(figsize=(10,60))
fig.subplots_adjust( ... )
The size of the picture matters.
«I’ve tried messing with hspace, but increasing it only seems to make all of the graphs smaller without resolving the overlap problem.»
Thus to make more white space and keep the sub plot size the total image needs to be bigger.
Brian Burns
19.5k8 gold badges82 silver badges74 bronze badges
answered Feb 26, 2013 at 10:25
The DemzThe Demz
6,9465 gold badges37 silver badges42 bronze badges
0
You could try the .subplot_tool()
plt.subplot_tool()
answered Jul 18, 2015 at 11:55
CiaranWelshCiaranWelsh
6,7259 gold badges48 silver badges96 bronze badges
0
- Resolving this issue when plotting a dataframe with
pandas.DataFrame.plot
, which usesmatplotlib
as the default backend.- The following works for whichever
kind=
is specified (e.g.'bar'
,'scatter'
,'hist'
, etc.).
- The following works for whichever
- Tested in
python 3.8.12
,pandas 1.3.4
,matplotlib 3.4.3
Imports and sample data
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# sinusoidal sample data
sample_length = range(1, 15+1)
rads = np.arange(0, 2*np.pi, 0.01)
data = np.array([np.sin(t*rads) for t in sample_length])
df = pd.DataFrame(data.T, index=pd.Series(rads.tolist(), name='radians'), columns=[f'freq: {i}x' for i in sample_length])
# default plot with subplots; each column is a subplot
axes = df.plot(subplots=True)
Adjust the Spacing
- Adjust the default parameters in
pandas.DataFrame.plot
- Change
figsize
: a width of 5 and a height of 4 for each subplot is a good place to start. - Change
layout
: (rows, columns) for the layout of subplots. sharey=True
andsharex=True
so space isn’t taken for redundant labels on each subplot.
- Change
- The
.plot
method returns a numpy array ofmatplotlib.axes.Axes
, which should be flattened to easily work with. - Use
.get_figure()
to extract theDataFrame.plot
figure object from one of theAxes
. - Use
fig.tight_layout()
if desired.
axes = df.plot(subplots=True, layout=(3, 5), figsize=(25, 16), sharex=True, sharey=True)
# flatten the axes array to easily access any subplot
axes = axes.flat
# extract the figure object
fig = axes[0].get_figure()
# use tight_layout
fig.tight_layout()
df
# display(df.head(3))
freq: 1x freq: 2x freq: 3x freq: 4x freq: 5x freq: 6x freq: 7x freq: 8x freq: 9x freq: 10x freq: 11x freq: 12x freq: 13x freq: 14x freq: 15x
radians
0.00 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
0.01 0.010000 0.019999 0.029996 0.039989 0.049979 0.059964 0.069943 0.079915 0.089879 0.099833 0.109778 0.119712 0.129634 0.139543 0.149438
0.02 0.019999 0.039989 0.059964 0.079915 0.099833 0.119712 0.139543 0.159318 0.179030 0.198669 0.218230 0.237703 0.257081 0.276356 0.295520
answered Nov 27, 2021 at 17:26
Trenton McKinneyTrenton McKinney
51.5k32 gold badges129 silver badges142 bronze badges
- This answer shows using
fig.tight_layout
after creating the figure. However,tight_layout
can be set directly when creating the figure, becausematplotlib.pyplot.subplots
accepts additional parameters with**fig_kw
. All additional keyword arguments are passed to thepyplot.figure
call. - See How to plot in multiple subplots for accessing and plotting in subplots.
import matplotlib.pyplot as plt
# create the figure with tight_layout=True
fig, axes = plt.subplots(nrows=4, ncols=4, figsize=(8, 8), tight_layout=True)
answered Aug 26, 2022 at 19:18
Trenton McKinneyTrenton McKinney
51.5k32 gold badges129 silver badges142 bronze badges
In this article, we will see how to set the spacing between subplots in Matplotlib in Python. Let’s discuss some concepts :
- Matplotlib : Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It was introduced by John Hunter in the year 2002.
- Subplots : The subplots() function in pyplot module of matplotlib library is used to create a figure and a set of subplots. Subplots are required when we want to show two or more plots in same figure.
Here, first we will see why setting of space is required.
Python3
import
numpy as np
import
matplotlib.pyplot as plt
x
=
np.array([
1
,
2
,
3
,
4
,
5
])
fig, ax
=
plt.subplots(
2
,
2
)
ax[
0
,
0
].plot(x, x)
ax[
0
,
1
].plot(x, x
*
2
)
ax[
1
,
0
].plot(x, x
*
x)
ax[
1
,
1
].plot(x, x
*
x
*
x)
plt.show()
Output:
Too much congested and very confusing
Set the spacing between subplots
As, we can see that the above figure axes values are too congested and very confusing. To solve this problem we need to set the spacing between subplots.
Steps Needed
- Import Libraries
- Create/ Load data
- Make subplot
- Plot subplot
- Set spacing between subplots.
Using tight_layout() method to set the spacing between subplots
The tight_layout() method automatically maintains the proper space between subplots.
Example 1: Without using pad
Python3
fig.tight_layout()
plt.show()
Output:
set the spacing between subplots in Matplotlib
Example 2: Using pad
Python3
fig.tight_layout(pad
=
5.0
)
plt.show()
Output:
set the spacing between subplots in Matplotlib
Using subplots_adjust() method to set the spacing between subplots
We can use the plt.subplots_adjust() method to change the space between Matplotlib subplots. The parameters wspace and hspace specify the space reserved between Matplotlib subplots. They are the fractions of axis width and height, respectively. And the parameters left, right, top and bottom parameters specify four sides of the subplots’ positions. They are the fractions of the width and height of the figure.
Python3
plt.subplots_adjust(left
=
0.1
,
bottom
=
0.1
,
right
=
0.9
,
top
=
0.9
,
wspace
=
0.4
,
hspace
=
0.4
)
plt.show()
Output:
Using subplots_tool() method to set the spacing between subplots
This method launches a subplot tool window for a figure. It provides an interactive method for the user to drag the bar in the subplot_tool to change the subplots’ layout.
Python3
plt.subplot_tool()
plt.show()
Output:
Using constrained_layout() to set the spacing between subplots
Here we are using the constrained_layout=True to set the spacing between the subplots in Matplotlib.
Python3
fig, ax
=
plt.subplots(
2
,
2
,
constrained_layout
=
True
)
ax[
0
,
0
].plot(x, x)
ax[
0
,
1
].plot(x, x
*
2
)
ax[
1
,
0
].plot(x, x
*
x)
ax[
1
,
1
].plot(x, x
*
x
*
x)
plt.show()
Output:
Often you may use subplots to display multiple plots alongside each other in Matplotlib. Unfortunately, these subplots tend to overlap each other by default.
The easiest way to resolve this issue is by using the Matplotlib tight_layout() function. This tutorial explains how to use this function in practice.
Create Subplots
Consider the following arrangement of 4 subplots in 2 columns and 2 rows:
import matplotlib.pyplot as plt #define subplots fig, ax = plt.subplots(2, 2) #display subplots plt.show()
Notice how the subplots overlap each other a bit.
Adjust Spacing of Subplots Using tight_layout()
The easiest way to resolve this overlapping issue is by using the Matplotlib tight_layout() function:
import matplotlib.pyplot as plt #define subplots fig, ax = plt.subplots(2, 2) fig.tight_layout() #display subplots plt.show()
Adjust Spacing of Subplot Titles
In some cases you may also have titles for each of your subplots. Unfortunately even the tight_layout() function tends to cause the subplot titles to overlap:
import matplotlib.pyplot as plt #define subplots fig, ax = plt.subplots(2, 2) fig.tight_layout() #define subplot titles ax[0, 0].set_title('First Subplot') ax[0, 1].set_title('Second Subplot') ax[1, 0].set_title('Third Subplot') ax[1, 1].set_title('Fourth Subplot') #display subplots plt.show()
The way to resolve this issue is by increasing the height padding between subplots using the h_pad argument:
import matplotlib.pyplot as plt #define subplots fig, ax = plt.subplots(2, 2) fig.tight_layout(h_pad=2) #define subplot titles ax[0, 0].set_title('First Subplot') ax[0, 1].set_title('Second Subplot') ax[1, 0].set_title('Third Subplot') ax[1, 1].set_title('Fourth Subplot') #display subplots plt.show()
Adjust Spacing of Overall Title
If you have an overall title, you can use the subplots_adjust() function to ensure that it doesn’t overlap with the subplot titles:
import matplotlib.pyplot as plt #define subplots fig, ax = plt.subplots(2, 2) fig.tight_layout(h_pad=2) #define subplot titles ax[0, 0].set_title('First Subplot') ax[0, 1].set_title('Second Subplot') ax[1, 0].set_title('Third Subplot') ax[1, 1].set_title('Fourth Subplot') #add overall title and adjust it so that it doesn't overlap with subplot titles fig.suptitle('Overall Title') plt.subplots_adjust(top=0.85) #display subplots plt.show()
You can find more Matplotlib tutorials here.
tight_layout()
Method to Change Matplotlib Space Between Subplotsplt.subplots_adjust()
Method to Change Space Between Subplots in Matplotlibplt.subplot_tool()
Method to Change Space Between Subplots in Matplotlib- Activate
constrained_layout=True
in Matplotlibsubplots
Function
We could use tight_layout()
, subplots_adjust()
and subplot_tool()
methods to change subplot size or space in Matplotlib. We can also improve space between Matplotlib space by setting constrained_layout=True
in the subplots()
function.
tight_layout()
Method to Change Matplotlib Space Between Subplots
The tight_layout()
method automatically maintains the proper space between subplots.
import numpy as np
import matplotlib.pyplot as plt
x=np.linspace(-3,3,100)
y1=np.sin(x)
y2=np.cos(x)
y3=1/(1+np.exp(-x))
y4=np.exp(x)
fig, ax = plt.subplots(2, 2)
ax[0, 0].plot(x, y1)
ax[0, 1].plot(x, y2)
ax[1, 0].plot(x, y3)
ax[1, 1].plot(x,y4)
ax[0, 0].set_title("Sine function")
ax[0, 1].set_title("Cosine function")
ax[1, 0].set_title("Sigmoid function")
ax[1, 1].set_title("Exponential function")
fig.tight_layout()
plt.show()
If we didn’t use the tight_layout()
method, one row would overlap with the title of the next.
import numpy as np
import matplotlib.pyplot as plt
x=np.linspace(-3,3,100)
y1=np.sin(x)
y2=np.cos(x)
y3=1/(1+np.exp(-x))
y4=np.exp(x)
fig, ax = plt.subplots(2, 2)
ax[0, 0].plot(x, y1)
ax[0, 1].plot(x, y2)
ax[1, 0].plot(x, y3)
ax[1, 1].plot(x,y4)
ax[0, 0].set_title("Sine function")
ax[0, 1].set_title("Cosine function")
ax[1, 0].set_title("Sigmoid function")
ax[1, 1].set_title("Exponential function")
plt.show()
plt.subplots_adjust()
Method to Change Space Between Subplots in Matplotlib
We can use the plt.subplots_adjust()
method to change the space between Matplotlib subplots.
import numpy as np
import matplotlib.pyplot as plt
x=np.linspace(-3,3,100)
y1=np.sin(x)
y2=np.cos(x)
y3=1/(1+np.exp(-x))
y4=np.exp(x)
fig, ax = plt.subplots(2, 2)
ax[0, 0].plot(x, y1)
ax[0, 1].plot(x, y2)
ax[1, 0].plot(x, y3)
ax[1, 1].plot(x,y4)
ax[0, 0].set_title("Sine function")
ax[0, 1].set_title("Cosine function")
ax[1, 0].set_title("Sigmoid function")
ax[1, 1].set_title("Exponential function")
plt.subplots_adjust(left=0.125,
bottom=0.1,
right=0.9,
top=0.9,
wspace=0.2,
hspace=0.35)
plt.show()
plt.subplots_adjust(left=0.125,
bottom=0.1,
right=0.9,
top=0.9,
wspace=0.2,
hspace=0.35)
wspace
and hspace
specify the space reserved between Matplotlib subplots. They are the fractions of axis width and height, respectively.
left
, right
, top
and bottom
parameters specify four sides of the subplots’ positions. They are the fractions of the width and height of the figure.
This method launches a subplot tool window for a figure.
import numpy as np
import matplotlib.pyplot as plt
im1=np.random.random((50,50))
im2=np.random.random((40,50))
im3=np.random.random((50,40))
im4=np.random.random((60,50))
plt.subplot(221)
plt.imshow(im1)
plt.subplot(222)
plt.imshow(im2)
plt.subplot(223)
plt.imshow(im3)
plt.subplot(224)
plt.imshow(im4)
plt.subplot_tool()
plt.show()
It provides an interactive method for the user to drag the bar in the subplot_tool
to change the subplots’ layout.
Activate constrained_layout=True
in Matplotlib subplots
Function
constrained_layout
adjusts subplots and decorations automatically to fit them in the figure as best as possible.
constrained_layout
must be activated before or during subplot creation as it optimizes the layout before every drawing step.
import numpy as np
import matplotlib.pyplot as plt
a=np.linspace(0,5,100)
figure, axes = plt.subplots(2,2, constrained_layout=True)
axes[0, 0].plot(x, np.exp(a))
axes[0, 1].plot(a, np.sin(a))
axes[1, 0].plot(a, np.cos(a))
axes[1, 1].plot(range(10))
axes[0, 0].set_title("subplot 1")
axes[0, 1].set_title("subplot 2")
axes[1, 0].set_title("subplot 3")
axes[1, 1].set_title("subplot 4")
plt.show()
Hello coders!! In this article, we will be learning about matplotlib subplot spacing. We know that matplotlib is a library used for the visualization of given data. Subplots are used in order to two or more plots in the same figure. We will now learn the different methods of matplotlib subplot spacing.
Different methods to add matplotlib subplot spacing:
- tight_layout()
- plt.subplot_tool()
- plt.subplot_adjust()
- constrained_layout parameter
Let us now discuss all these methods in detail.
Method 1: tight_layout for matplotlib subplot spacing:
The tight_layout() is a method available in the pyplot module of the matplotlib library. It is used to automatically adjust subplot parameters to give specified padding.
Syntax:
matplotlib.pyplot.tight_layout(pad=1.08, h_pad=None, w_pad=None, rect=None)
Parameters:
- pad: padding between the figure edge and the edges of subplots
- h_pad, w_pad: padding (height/width) between edges of adjacent subplots
- rect: a rectangle in the normalized figure coordinate that the whole subplots area will fit into
Return Value:
No return value.
import numpy as np import matplotlib.pyplot as plt x=np.array([1, 2, 3, 4, 5]) fig, ax = plt.subplots(2, 2) ax[0, 0].plot(x, x) ax[0, 1].plot(x, x*x) ax[1, 0].plot(x, x*x*x) ax[1, 1].plot(x, x*x*x*x) ax[0, 0].set_title("Linear") ax[0, 1].set_title("Square") ax[1, 0].set_title("Cube") ax[1, 1].set_title("Fourth power") fig.tight_layout() plt.show()
Output:
In this example, we used the tight_layout() method for automatic spacing between the subplots. We used four subplots, all showing the relation of x with different power. As we can see, all the subplots are properly spaced. However, if we did not use the tight_layout() method, one row would overlap with the title of the next.
This method is also available in the pyplot module of the matplotlib library. It is used to launch a subplot tool window for a figure.
Syntax:
matplotlib.pyplot.subplot_tool(targetfig=None)
Parameters:
No parameter.
Return Value:
No return value.
import numpy as np import matplotlib.pyplot as plt x=np.array([1, 2, 3, 4, 5]) fig, ax = plt.subplots(2, 2) ax[0, 0].plot(x, x) ax[0, 1].plot(x, x*x) ax[1, 0].plot(x, x*x*x) ax[1, 1].plot(x, x*x*x*x) ax[0, 0].set_title("Linear") ax[0, 1].set_title("Square") ax[1, 0].set_title("Cube") ax[1, 1].set_title("Fourth power") plt.subplot_tool() plt.show()
Output:
We have used the same example. Here, we have used the plt.subplot_tool() that provides us with a interactive method in which the user can drag the bar to adjust the spacing and the layout of the subplots.
Method 3: plt.subplot_adjust() for matplotlib subplot spacing:
This is a function available in the pyplot module of the matplotlib library. It is used to tune the subplot layout.
Syntax:
matplotlib.pyplot.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)
Parameters:
- left: left side of the subplots
- right: right side of the subplots
- bottom: bottom of the subplots
- top: top of the subplots
- wspace: amount of width reserved for space between subplots
- hspace: amount of height reserved for space between subplots
import numpy as np import matplotlib.pyplot as plt x=np.array([1, 2, 3, 4, 5]) fig, ax = plt.subplots(2, 2) ax[0, 0].plot(x, x) ax[0, 1].plot(x, x*x) ax[1, 0].plot(x, x*x*x) ax[1, 1].plot(x, x*x*x*x) ax[0, 0].set_title("Linear") ax[0, 1].set_title("Square") ax[1, 0].set_title("Cube") ax[1, 1].set_title("Fourth power") plt.subplots_adjust(left=0.1, bottom=0.1, right=0.9, top=0.9, wspace=0.4, hspace=0.4) plt.show()
Output:
We have used the same example again. But this time, we have used plt.subplot_adjust() to adjust the layout of the figure as per our preference.
Method 4: Achieving Subplot spacing Using constrained_layout parameter
The constrained_layout parameter is used to adjust the subplots automatically in order to fit them in the best possible way. This parameter must be activated in order to optimize the layout.
import numpy as np import matplotlib.pyplot as plt x=np.array([1, 2, 3, 4, 5]) fig, ax = plt.subplots(2, 2, constrained_layout = True) ax[0, 0].plot(x, x) ax[0, 1].plot(x, x*x) ax[1, 0].plot(x, x*x*x) ax[1, 1].plot(x, x*x*x*x) ax[0, 0].set_title("Linear") ax[0, 1].set_title("Square") ax[1, 0].set_title("Cube") ax[1, 1].set_title("Fourth power") plt.show()
Output:
As you can see, we have activated the constrained_layout parameter. As a result, we get an optimized output.
Conclusion:
With this, we come to an end with this article. We learned four different methods for matplotlib spacing of subplots. We also saw detailed examples for each.
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!
In this Python tutorial, we will discuss Matplotlib subplots_adjust in python, which lets us work with refining multiple plots within a single figure and we also cover the following topics:
- Matplotlib subplots_adjust
- Matplotlib subplots_adjust tight_layout
- Matplotlib subplots spacing
- Matplotlib subplots_adjust height and hspace
- Matplotlib subplots_adjust figure size
- Matplotlib subplots_adjust wspace and width
- Matplotlib subplots_adjust bottom
- Matplotlib subplots_adjust right
- Matplotlib subplots_adjust not working
The subplots_adjust() is a function in matplotib library, which is used to adjust or refine the subplot structure or design.
The syntax for subplots_adjust() is as follows:
matplotlib.pyplot.subplots_adjust(left=None,bottom=None,right=None,top=None,wspace=None,hspace=None)
In the above syntax the following parameters are used which are outlined below:
- left: specifies the left position of the subplots of the figure. Default size is 0.125.
- right: specifies the right position of the subplots of the figure. Default size is 0.9.
- bottom: specifies the bottom position of the subplots of the figure. Default size is 0.1.
- top: specifies the top position of the subplots of the figure. Default size is 0.9.
- wspace: specifies the size of width for white space between subplots (called padding), as a fraction of the average Axes width. Default size is 0.2.
- hspace: specifies the size of height for white space between subplots (called padding), as a fraction of the average Axes height. Default size is 0.2.
Let’s do an example for understanding the concepts:
Code#1
# Importing libraries
import numpy as np
import matplotlib.pyplot as plt
x1 = [2 , 4 , 6 , 8 , 10]
x2 = [5 , 10 , 15 , 20 , 25]
fig = plt.figure()
ax = fig.subplots()
ax.plot(x1,x2)
fig.show()
The above code #1 is just a simple matplotlib subplot code.
Code#2
# Importing libraries
import numpy as np
import matplotlib.pyplot as plt
x1 = [2 , 4 , 6 , 8 , 10]
x2 = [5 , 10 , 15 , 20 , 25]
fig = plt.figure()
ax = fig.subplots()
ax.plot(x1,x2)
fig.subplots_adjust(right = 2)
fig.show()
In the above code #2, we implement the subplots_adjust function with parameter right.
Now, let’s see the difference in both the outputs of the code, so we clearly understand what basically subplots_adjust function does.
Now from the above two codes and their outputs, we clearly see that by using the subplots_adjust(), we adjust the right position of the subplot by 2.
Conclusion! matplotlib.pyplot.subplots_adjust() function reshape the design of the subplot by changing its positions.
Read: Matplotlib best fit line
Matplotlib subplots_adjust tight_layout
The subplots_adjust tight_layout() is a function in matplotib library, which is used to automatically adjust the proper space between the subplots so that it fits into the figure area.
The syntax is as follow:
matplotlib.pyplot.tight_layout(pad=10.8, h_pad=None, w_pad=None, rect=None)
In the above syntax, the following parameters are used which are outlined below:
- pad: specifies the size of white space ( called Padding ) between edges of subplots. By default, it is 1.08
- h_pad: specifies the size of the height for Padding between edges of the subplots.
- w_pad: specifies the size of the width for Padding between edges of the subplots.
- rect: specifies the size of the figure area into which the subplots fit.
When to use tight_layout():
- When axis labels to titles go outside the figure area.
- When we have more than one subplots in a figure area, and we see labels or titles of different subplots overlapping each other.
- When we have multiple subplots in a figure area, and we see the subplots are of different sizes.
- When we have multiple subpots in a figure area, and we want to adjust extra padding around the figure and between the subplots.
Let’s do an example for understanding the concept:
Code#1
# Importing libraries
import numpy as np
import matplotlib.pyplot as plt
x1= [2,4,6]
y1= [3,6,9]
x2= [5,10,15]
y2= [6,12,18]
x3= [2,4,6]
y3= [3,6,9]
x4= [5,10,15]
y4= [6,12,18]
fig, ax = plt.subplots(2, 2)
ax[0, 0].plot(x1, y1)
ax[0, 1].plot(x2, y2)
ax[1, 0].plot(x3, y3)
ax[1, 1].plot(x4,y4)
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")
plt.show()
The above code#1 is just a simple matplotlib subplot code in which we have multiple subplots in a figure area.
Code#2
# Importing Libraries
import numpy as np
import matplotlib.pyplot as plt
x1= [2,4,6]
y1= [3,6,9]
x2= [5,10,15]
y2= [6,12,18]
x3= [2,4,6]
y3= [3,6,9]
x4= [5,10,15]
y4= [6,12,18]
fig, ax = plt.subplots(2, 2)
ax[0, 0].plot(x1, y1)
ax[0, 1].plot(x2, y2)
ax[1, 0].plot(x3, y3)
ax[1, 1].plot(x4,y4)
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")
fig.tight_layout()
plt.show()
In the above Code#2, we have to implement the tight_layout function.
Now, let’s see the difference in both the outputs of the code, so we clearly understand what basically tight_layout function does.
In the above output, we have seen that labels of different axes overlapping each other.
In the above output, we have seen that by using the tight_layout function we adjust the spacing between subplots in a figure area to avoid overlapping.
Conclusion! matplotlib.pyplot.tight_layout() function adjusts the subplots so it fits into the figure area perfectly.
Read: Matplotlib subplot tutorial
Matplotlib subplots spacing
Why do we need Spacing!
When we deal with subplots we have to plot multiple subplots in the figure area. Sometimes we see that axes for multiple subplots in a figure area start overlapping or axes values are too confusing and overcrowded.
So to solve these problems we need to set the spacing between subplots.
Ways To Solve Spacing:
- Using tight_layout() function
- Using subplots_adjust() function
- Using subplot_tool() function
Using tight_layout() function
tight_layout() function adjusts the spacing between subplots automatically.
The syntax for the above:
matplotlib.pyplot.tight_layout()
Let’s understand with the help of an example:
# Importing Libraries
import numpy as np
import matplotlib.pyplot as plt
x1= [2,4,6]
y1= [3,6,9]
x2= [5,10,15]
y2= [6,12,18]
x3= [2,4,6]
y3= [3,6,9]
x4= [5,10,15]
y4= [6,12,18]
fig, ax = plt.subplots(2, 2)
ax[0, 0].plot(x1, y1)
ax[0, 1].plot(x2, y2)
ax[1, 0].plot(x3, y3)
ax[1, 1].plot(x4,y4)
fig.tight_layout()
plt.show()
From the above example, we conclude that by using the tight_layout() function the spacing between subplots is proper.
Read Matplotlib plot_date
Using subplots_adjust() function
subplots_adjust() function changes the space between subplots. By using parameters left, right, top, bottom, wspace, hspace, we can adjust the subplot’s position.
The syntax for the above:
matplotlib.pyplot.subplots_adjust(left=None, bottom= None, right=None, top=None, wspace=None, hspace=None)
Let’s understand with the help of an example:
# Importing Libraries
import numpy as np
import matplotlib.pyplot as plt
x1= [2,4,6]
y1= [3,6,9]
x2= [5,10,15]
y2= [6,12,18]
x3= [2,4,6]
y3= [3,6,9]
x4= [5,10,15]
y4= [6,12,18]
fig, ax = plt.subplots(2, 2)
ax[0, 0].plot(x1, y1)
ax[0, 1].plot(x2, y2)
ax[1, 0].plot(x3, y3)
ax[1, 1].plot(x4,y4)
plt.subplots_adjust(left=0.5, bottom=0.5, right=1, top=1, wspace=0.9,hspace=0.9)
plt.show()
From the above example, we conclude that by using the subplots_adjust() function the spacing between subplots is proper.
Using subplot_tool() function
subplot_tool() method provides a slider to adjust subplot spacing. It is an interactive method in which users drag the bar to do adjustments as per their needs.
The syntax for the above:
matplotlib.pyplot.subplot_tool()
Let’s understand with the help of an example:
# Importing Libraries
import numpy as np
import matplotlib.pyplot as plt
x1= [2,4,6]
y1= [3,6,9]
x2= [5,10,15]
y2= [6,12,18]
x3= [2,4,6]
y3= [3,6,9]
x4= [5,10,15]
y4= [6,12,18]
fig, ax = plt.subplots(2, 2)
ax[0, 0].plot(x1, y1)
ax[0, 1].plot(x2, y2)
ax[1, 0].plot(x3, y3)
ax[1, 1].plot(x4,y4)
plt.subplot_tool()
plt.show()
From the above example, we conclude that by using the subplot_tool() function we can adjust spacing by using the slider.
Read: Matplotlib plot bar chart
Matplotlib subplot_adjust height or hspace
When we deal with subplots we have to plot multiple subplots in the figure area. Sometimes the problem of overlapping starts occurring so to avoid that we need to adjust the height.
Ways to Adjust Height:
- Using tight_layout() function
- Using subplots_adjust() function
- Using subplot_tool() function
Using tight_layout() function
tight_layout() function adjusts the height of white space ( Called Padding ) between subplots automatically.
Syntax as below:
matplotlib.pyplot.tight_layout()
Let’s understand it with the help of an example:
# Importing Libraries
import numpy as np
import matplotlib.pyplot as plt
x1= [1,2,3]
y1= [5,6,9]
x2= [5,10,20]
y2= [6,12,15]
x3= [2,5,6]
y3= [3,6,9]
x4= [7,8,15]
y4= [6,12,18]
fig, ax = plt.subplots(2, 2)
ax[0, 0].plot(x1, y1)
ax[0, 1].plot(x2, y2)
ax[1, 0].plot(x3, y3)
ax[1, 1].plot(x4,y4)
fig.tight_layout()
plt.show()
From the above example, we conclude that by using the tight_layout() function the height space between subplots is exact as needed.
Using subplots_adjust() function
subplots_adjust() function changes the space between subplots. By using parameter hspace we can adjust the height of the Padding between subplots.
The syntax for this is as below:
matplotlib.pyplot.subplots_adjust(hspace=None)
Let’s understand this with the help of an example:
# Importing Libraries
import numpy as np
import matplotlib.pyplot as plt
x1= [1,2,3]
y1= [5,6,9]
x2= [5,10,20]
y2= [6,12,15]
x3= [2,5,6]
y3= [3,6,9]
x4= [7,8,15]
y4= [6,12,18]
fig, ax = plt.subplots(2, 2)
ax[0, 0].plot(x1, y1)
ax[0, 1].plot(x2, y2)
ax[1, 0].plot(x3, y3)
ax[1, 1].plot(x4,y4)
fig.subplots_adjust(hspace=0.9)
plt.show()
From the above example, we conclude that by using the subplots_adjust() function we can tune the height of the padding.
Read Add text to plot matplotlib in Python
Using subplot_tool() function
subplot_tool() method provides a slider to adjust subplot height. It is an interactive tool in which users darg the height bar to do adjustments as per their needs.
The syntax for the above:
matplotlib.pyplot.subplot_tool()
Let’s understand it with the help of an example:
# Importing Libraries
import numpy as np
import matplotlib.pyplot as plt
x1= [1,2,3]
y1= [5,6,9]
x2= [5,10,20]
y2= [6,12,15]
x3= [2,5,6]
y3= [3,6,9]
x4= [7,8,15]
y4= [6,12,18]
fig, ax = plt.subplots(2, 2)
ax[0, 0].plot(x1, y1)
ax[0, 1].plot(x2, y2)
ax[1, 0].plot(x3, y3)
ax[1, 1].plot(x4,y4)
plt.subplot_tool()
plt.show()
In the above example, we can drag the slider to adjust the height of the subplots in a figure area.
Read: What is matplotlib inline
Matplotlib subplots_adjust figure size
As we have already study, that by using function subplots() we can create multiple graphs within the same figure area. But the exception occurs the subplots method only creates subplots of the same size or adjusts the size automatically.
Now the problem comes! What to do if we want to create subplots of different sizes within the area.
Hurrah! We have a solution for this problem. So let’s learn it.
For changing the size of subplots within the same figure area according to your choice using the method add_gridspec(). It is a powerful solution if we want to change the size of multiple subplots but it takes time for creating multiple subplots of the same size.
- In this method, we have defined the location in which we want to create a plot and also specify each subplot individually.
- We have to specify the number of rows and columns of the grid as the input parameter of the add_gridspec() method.
- After the initialization of grid size, we can adjust the size according to your relevance by varying the input coordinates in the add_subplot() function.
- The coordinates of the axes which we enter as parameters in the sub_plot() method specify the initial and final position of the plot (i.e. rows and columns).
To specify the initial and final position of the plot you should have some knowledge of indexing and slicing.
Tip! Don’t use add_gridspec() for creating subplots of the same size.
So, Let’s understand it with the help of an example:
# Importing Libraries.
import matplotlib.pyplot as plt
# .figure() method is used to plot a fig and parameter constrained_layout=True is used to plot figure nicely distributed.
fig = plt.figure(constrained_layout=True)
# Creating the subplots with .add_gridspec().
ax = fig.add_gridspec(3, 3)
# .add_subplot() shows initial and final position of the plot.
ax1 = fig.add_subplot(ax[0, 0:1]) # Plot is located in the first row and has a width of 1/3 of the entire gride.
ax1.set_title('[0, 0:1]')
ax1 = fig.add_subplot(ax[0:, -1]) # Plot is located in one column wide but has a height of entire grid.
ax1.set_title('[0:, -1]')
ax1 = fig.add_subplot(ax[2:, 0:2]) # Plot is located in last three rows and first two columns.
ax1.set_title('[2:, 0:2]')
# Display the Plot
plt.show()
Here is the output of the above code.
In the above example, we have concluded that by using the add_gridspec() method we can change the size of multiple subplots in a figure area according to your preference.
Conclusion! Steps to change the figure size:
- Creat the subplots with add_gridspec() method and specify their distribution.
- Use the add_subplot() method to specify the initial and final position of the subplots.
- Use slicing and indexing to specify the location of the subplots within the region.
Read: Python plot multiple lines using Matplotlib
Matplotlib subplot_adjust width or wspace
When we deal with subplots we have to plot multiple subplots in the figure area. Sometimes the problem of overlapping starts occurring so to avoid that we need to adjust the width.
Ways to Adjust wspace:
- Using tight_layout() function
- Using subplots_adjust() function
- Using subplot_tool() function
Using tight_layout() function
tight_layout() function adjusts the width of padding between the subplots automatically as per the requirement. This means that the width of the white space between the subplots with a figure area is tuned.
Syntax as below:
matplotlib.pyplot.tight_layout()
Let’s understand it with the help of an example:
# Importing Libraries
import numpy as np
import matplotlib.pyplot as plt
x1= [0.2, 0.4, 0.6, 0.8, 1]
y1= [0.3, 0.6, 0.8, 0.9, 1.5]
x2= [2, 6, 7, 9, 10]
y2= [3, 4, 6, 9, 12]
x3= [5, 8, 12]
y3= [3, 6, 9]
x4= [7, 8, 15]
y4= [6, 12, 18]
fig, ax = plt.subplots(2, 2)
ax[0, 0].plot(x1, y1)
ax[0, 1].plot(x2, y2)
ax[1, 0].plot(x3, y3)
ax[1, 1].plot(x4,y4)
fig.tight_layout()
plt.show()
From the above example, we concluded that by using the tight_layout() method the wspace or width of the padding between the subplots is exact without any overlapping.
Using subplots_adjust() function
subplots_adjust() method changes the space between subplots. By using parameter wspace we can adjust the width of white space between the subplots (called Padding). Sometimes we refer wspace also as the width of the subplots.
The syntax for this is as below:
matplotlib.pyplot.subplots_adjust(wspace=None)
Let’s understand this with the help of an example:
# Importing Libraries
import numpy as np
import matplotlib.pyplot as plt
x1= [0.2, 0.4, 0.6, 0.8, 1]
y1= [0.3, 0.6, 0.8, 0.9, 1.5]
x2= [2, 6, 7, 9, 10]
y2= [3, 4, 6, 9, 12]
x3= [5, 8, 12]
y3= [3, 6, 9]
x4= [7, 8, 15]
y4= [6, 12, 18]
fig, ax = plt.subplots(2, 2)
ax[0, 0].plot(x1, y1)
ax[0, 1].plot(x2, y2)
ax[1, 0].plot(x3, y3)
ax[1, 1].plot(x4,y4)
fig.subplots_adjust(wspace=10)
plt.show()
From the above example, we conclude that by using the subplots_adjust() method we can tune the width of the padding between subplots within a region.
Using subplot_tool() function
subplot_tool() function provides a slider to adjust subplot width or wspace. It is an interactive way to adjust the width of the subplots. Users can drag the wspace bar to adjust the width of the subplots.
The syntax for the above:
matplotlib.pyplot.subplot_tool()
Let’s understand it with the help of an example:
# Importing Libraries
import numpy as np
import matplotlib.pyplot as plt
x1= [0.2, 0.4, 0.6, 0.8, 1]
y1= [0.3, 0.6, 0.8, 0.9, 1.5]
x2= [2, 6, 7, 9, 10]
y2= [3, 4, 6, 9, 12]
x3= [5, 8, 12]
y3= [3, 6, 9]
x4= [7, 8, 15]
y4= [6, 12, 18]
fig, ax = plt.subplots(2, 2)
ax[0, 0].plot(x1, y1)
ax[0, 1].plot(x2, y2)
ax[1, 0].plot(x3, y3)
ax[1, 1].plot(x4,y4)
plt.subplot_tool()
plt.show()
In the above example, we have to click on the slider to adjust the subplot param wspace or we say the width of subplots.
Read: Matplotlib plot a line
Matplotlib subplot_adjust bottom
When we deal with subplots we have to plot multiple graphs in the figure area. Sometimes the problem of overlapping starts occurring. We encounter a problem that tick mark labels or an x-axis label flaps or overrun on tick marks and axis labels of another subplot in an area. To overcome this problem we have to adjust the bottom margin.
Ways to Adjust bottom:
- Using tight_layout() method
- Using subplots_adjust() method
- Using subplot_tool() method
Using tight_layout() method
tight_layout() function adjusts the bottom margin between the subplots automatically. We can also say that it automatically creates a room for tick marks labels or an x-axis label.
Syntax as below:
matplotlib.pyplot.tight_layout()
Let’s understand the concept with an example:
# Import Libraries
import numpy as np
import matplotlib.pyplot as plt
x1= [2,4,6]
y1= [3,6,9]
x2= [5,10.9,15]
y2= [6,12,18]
x3= [2,4.5,6]
y3= [3,6,9]
x4= [5,10]
y4= [6,12]
fig, ax = plt.subplots(2, 2)
ax[0, 0].plot(x1, y1)
ax[0, 1].plot(x2, y2)
ax[1, 0].plot(x3, y3)
ax[1, 1].plot(x4, y4)
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")
fig.tight_layout()
plt.show()
From the above example, we concluded that by using the tight_layout() function the bottom margin increases its size automatically to avoid overlapping.
Using subplots_adjust() method
subplots_adjust() method changes the space between subplots. By using parameter bottom we can tune the bottom margin of the subplots. By default, the value of the bottom is 0.1. We have to increase the value to increase the size of the bottom margin.
Syntax as below:
matplotlib.pyplot.subplots_adjust(bottom=None)
Let’s understand this with the help of an example:
# Import Libraries
import numpy as np
import matplotlib.pyplot as plt
x = [2,4,6,8,10]
y = [5,10,15,20,25]
fig = plt.figure()
ax = fig.subplots()
ax.plot(x, y)
fig.subplots_adjust(bottom = 0.2)
fig.show()
From the above example, we conclude that by using the subplots_adjust() method we can increase or decrease the size of the bottom margin in a figure area.
Using subplot_tool() method
subplot_tool() function provides an interactive way to adjust the bottom margin of the subplots. This method provides a slider to adjust the subplot bottom margin. Users can drag the bottom bar to tune the margin space of the subplots.
The syntax for the above:
matplotlib.pyplot.suplot_tool()
Let’s understand it with the help of an example:
# Importing Libraries
import numpy as np
import matplotlib.pyplot as plt
x1= [0.2, 0.4, 0.6, 0.8, 1]
y1= [0.3, 0.6, 0.8, 0.9, 1.5]
x2= [2, 6, 7, 9, 10]
y2= [3, 4, 6, 9, 12]
x3= [5, 8, 12]
y3= [3, 6, 9]
x4= [7, 8, 15]
y4= [6, 12, 18]
fig, ax = plt.subplots(2, 2)
ax[0, 0].plot(x1, y1)
ax[0, 1].plot(x2, y2)
ax[1, 0].plot(x3, y3)
ax[1, 1].plot(x4,y4)
plt.subplot_tool()
plt.show()
In the above example, we have to click on the slider to adjust the subplot param bottom.
Read: How to install matplotlib python
Matplotlib subplot_adjust Right
When we deal with subplots we have to plot multiple subplots in the figure area. Sometimes the problem of overlapping starts occurring so to avoid that we need to adjust right.
To perfectly fit subplots in a region we have to increase the right margin so that figure can adjust without flapping and to make the room available for legends we have to decrease the size of the right margin.
Ways to Adjust right:
- Using tight_layout() function
- Using subplots_adjust() function
- Using subplot_tool() function
Using tight_layout() function
tight_layout() function adjusts the size of the right margin between the subplots automatically. Without any user interface the design of this method perfect figure area containing multiple subplots.
The syntax for this is given below:
matplotlib.pyplot.tight_layout()
Let’s understand it with the help of an example:
# Importing Libraries
import numpy as np
import matplotlib.pyplot as plt
x1= [0.2, 0.4, 0.6, 0.8, 1]
y1= [0.3, 0.6, 0.8, 0.9, 1.5]
x2= [2, 6, 7, 9, 10]
y2= [3, 4, 6, 9, 12]
x3= [5, 8, 12]
y3= [3, 6, 9]
x4= [7, 8, 15]
y4= [6, 12, 18]
fig, ax = plt.subplots(2, 2)
ax[0, 0].plot(x1, y1)
ax[0, 1].plot(x2, y2)
ax[1, 0].plot(x3, y3)
ax[1, 1].plot(x4,y4)
fig.tight_layout()
plt.show()
From the above example, we concluded that by using the tight_layout() method the right margin between subplots gets perfect.
Using subplots_adjust() function
subplots_adjust() method changes the space between subplots. By using parameter right we can adjust the margin size from the right side. By default, the value of the right parameter is 0.9. We have to increase it or decrease it as per our needs.
The syntax for this is as below:
matplotlib.pyplot.subplots_adjust(right=None)
Let’s understand this concept with the help of an example:
# Import Libraries
import numpy as np
import matplotlib.pyplot as plt
x = [2,4,6,8,10]
y = [5,10,15,6.3,25]
fig = plt.figure()
ax = fig.subplots()
ax.plot(x, y)
fig.subplots_adjust(right = 0.9)
fig.show()
From the above-coded example, we concluded that by using the subplots_adjust() method we can tune the right margin of subplots.
Using subplot_tool() function
subplot_tool() function provides a slider to adjust the subplot right margin. It is an interactive way to refine the right side margin of the subplots. Users have to drag the right bar to tune the right margin.
The syntax for the above:
matplotlib.pyplot.subplot_tool()
Let’s understand it with the help of an example:
# Importing Libraries
import numpy as np
import matplotlib.pyplot as plt
x1= [0.2, 0.4, 0.6, 0.8, 1]
y1= [0.3, 0.6, 0.8, 0.9, 1.5]
x2= [2, 6, 7, 9, 10]
y2= [3, 4, 6, 9, 12]
x3= [5, 8, 12]
y3= [3, 6, 9]
x4= [7, 8, 15]
y4= [6, 12, 18]
fig, ax = plt.subplots(2, 2)
ax[0, 0].plot(x1, y1)
ax[0, 1].plot(x2, y2)
ax[1, 0].plot(x3, y3)
ax[1, 1].plot(x4,y4)
plt.subplot_tool()
plt.show()
In the above example, we have to click on the slider to adjust the subplot right param to adjust the margin.
Read: modulenotfounderror: no module named ‘matplotlib’
Matplotlib subplot_adjust not working
Not working in the conditions in which we are not able to perform your task. We can also say that the condition in which errors or some obstacles occur in coding and you are not getting the desired output.
Not working conditions occur due to runtime error or maybe syntax error.
Let’s discuss some common, not working conditions:
Error#1
If you encounter such kind of error:
- Check whether the libaraires are imported or not.
- Check whether you mention ‘plt’ as nickname of any imported library or not
Error#2
If you encounter such kind of error:
Most programmers do this mistake. It’s a very common syntax error.
- Note that attribute name is subplots_adjust not subplot_adjust. Take care of such errors.
Error#3
If you encounter such kind of error you will not able to get the slider to adjust the subplot param.
- Remember subplot_tool is attribute of plt. So rectify this object name.
Error#4
If you encounter such kind of an error:
- The default value of top is 0.9 and bottom is 0.1. To remove this error note that bottom should be less than or equal to top value.
You may also like to read the following articles.
- Matplotlib log log plot
- Horizontal line matplotlib
- Matplotlib scatter plot legend
- Matplotlib multiple bar chart
- Put legend outside plot matplotlib
In this Python tutorial, we have discussed the “Matplotlib subplot_adjust” and we have also covered some examples related to it. There are the following topics that we have discussed in this tutorial.
- Matplotlib subplots_adjust
- Matplotlib subplots_adjust tight_layout
- Matplotlib subplots_adjust spacing
- Matplotlib subplots_adjust height and hspace
- Matplotlib subplots_adjust figure size
- Matplotlib subplots_adjust width and wspace
- Matplotlib subplots_adjust bottom
- Matplotlib subplots_adjust right
- Matplotlib subplots_adjust not working
Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.