Plt Leave Plot Up Even Though Script Continues
Note
Click here to download the full example code
Tight Layout guide#
How to use tight-layout to fit plots within your figure cleanly.
tight_layout automatically adjusts subplot params so that the subplot(s) fits in to the figure area. This is an experimental feature and may not work for some cases. It only checks the extents of ticklabels, axis labels, and titles.
An alternative to tight_layout is constrained_layout.
Simple Example#
In matplotlib, the location of axes (including subplots) are specified in normalized figure coordinates. It can happen that your axis labels or titles (or sometimes even ticklabels) go outside the figure area, and are thus clipped.
To prevent this, the location of axes needs to be adjusted. For subplots, this can be done manually by adjusting the subplot parameters using Figure.subplots_adjust
. Figure.tight_layout
does this automatically.
Note that matplotlib.pyplot.tight_layout()
will only adjust the subplot params when it is called. In order to perform this adjustment each time the figure is redrawn, you can call fig.set_tight_layout(True)
, or, equivalently, set rcParams["figure.autolayout"]
(default: False
) to True
.
When you have multiple subplots, often you see labels of different axes overlapping each other.
plt . close ( 'all' ) fig , (( ax1 , ax2 ), ( ax3 , ax4 )) = plt . subplots ( nrows = 2 , ncols = 2 ) example_plot ( ax1 ) example_plot ( ax2 ) example_plot ( ax3 ) example_plot ( ax4 )
tight_layout()
will also adjust spacing between subplots to minimize the overlaps.
tight_layout()
can take keyword arguments of pad, w_pad and h_pad. These control the extra padding around the figure border and between subplots. The pads are specified in fraction of fontsize.
fig , (( ax1 , ax2 ), ( ax3 , ax4 )) = plt . subplots ( nrows = 2 , ncols = 2 ) example_plot ( ax1 ) example_plot ( ax2 ) example_plot ( ax3 ) example_plot ( ax4 ) plt . tight_layout ( pad = 0.4 , w_pad = 0.5 , h_pad = 1.0 )
tight_layout()
will work even if the sizes of subplots are different as far as their grid specification is compatible. In the example below, ax1 and ax2 are subplots of a 2x2 grid, while ax3 is of a 1x2 grid.
It works with subplots created with subplot2grid()
. In general, subplots created from the gridspec (Arranging multiple Axes in a Figure) will work.
plt . close ( 'all' ) fig = plt . figure () ax1 = plt . subplot2grid (( 3 , 3 ), ( 0 , 0 )) ax2 = plt . subplot2grid (( 3 , 3 ), ( 0 , 1 ), colspan = 2 ) ax3 = plt . subplot2grid (( 3 , 3 ), ( 1 , 0 ), colspan = 2 , rowspan = 2 ) ax4 = plt . subplot2grid (( 3 , 3 ), ( 1 , 2 ), rowspan = 2 ) example_plot ( ax1 ) example_plot ( ax2 ) example_plot ( ax3 ) example_plot ( ax4 ) plt . tight_layout ()
Although not thoroughly tested, it seems to work for subplots with aspect != "auto" (e.g., axes with images).
Caveats#
-
tight_layout
considers all artists on the axes by default. To remove an artist from the layout calculation you can callArtist.set_in_layout
. -
tight_layout
assumes that the extra space needed for artists is independent of the original location of axes. This is often true, but there are rare cases where it is not. -
pad=0
can clip some texts by a few pixels. This may be a bug or a limitation of the current algorithm and it is not clear why it happens. Meanwhile, use of pad larger than 0.3 is recommended.
Use with GridSpec#
GridSpec has its own GridSpec.tight_layout
method (the pyplot api pyplot.tight_layout
also works).
You may provide an optional rect parameter, which specifies the bounding box that the subplots will be fit inside. The coordinates must be in normalized figure coordinates and the default is (0, 0, 1, 1).
However, we do not recommend that this be used to manually construct more complicated layouts, like having one GridSpec in the left and one in the right side of the figure. For these use cases, one should instead take advantage of Nested Gridspecs, or the Figure subfigures.
Legends and Annotations#
Pre Matplotlib 2.2, legends and annotations were excluded from the bounding box calculations that decide the layout. Subsequently these artists were added to the calculation, but sometimes it is undesirable to include them. For instance in this case it might be good to have the axes shrink a bit to make room for the legend:
However, sometimes this is not desired (quite often when using fig.savefig('outname.png', bbox_inches='tight')
). In order to remove the legend from the bounding box calculation, we simply set its bounding leg.set_in_layout(False)
and the legend will be ignored.
Use with AxesGrid1#
While limited, mpl_toolkits.axes_grid1
is also supported.
Colorbar#
If you create a colorbar with Figure.colorbar
, the created colorbar is drawn in a Subplot as long as the parent axes is also a Subplot, so Figure.tight_layout
will work.
Another option is to use the AxesGrid1 toolkit to explicitly create an Axes for the colorbar.
Total running time of the script: ( 0 minutes 5.470 seconds)
Gallery generated by Sphinx-Gallery
alngindabubabsizarly.blogspot.com
Source: https://matplotlib.org/stable/tutorials/intermediate/tight_layout_guide.html