.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "tutorials/intermediate/tight_layout_guide.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note Click :ref:`here ` to download the full example code .. rst-class:: sphx-glr-example-title .. _sphx_glr_tutorials_intermediate_tight_layout_guide.py: ================== 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 :doc:`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. .. GENERATED FROM PYTHON SOURCE LINES 26-46 .. code-block:: default import matplotlib.pyplot as plt import numpy as np plt.rcParams['savefig.facecolor'] = "0.8" def example_plot(ax, fontsize=12): ax.plot([1, 2]) ax.locator_params(nbins=3) ax.set_xlabel('x-label', fontsize=fontsize) ax.set_ylabel('y-label', fontsize=fontsize) ax.set_title('Title', fontsize=fontsize) plt.close('all') fig, ax = plt.subplots() example_plot(ax, fontsize=24) .. image:: /tutorials/intermediate/images/sphx_glr_tight_layout_guide_001.png :alt: Title :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 48-52 To prevent this, the location of axes needs to be adjusted. For subplots, this can be done by adjusting the subplot params (:ref:`howto-subplots-adjust`). Matplotlib v1.1 introduced `.Figure.tight_layout` that does this automatically for you. .. GENERATED FROM PYTHON SOURCE LINES 52-57 .. code-block:: default fig, ax = plt.subplots() example_plot(ax, fontsize=24) plt.tight_layout() .. image:: /tutorials/intermediate/images/sphx_glr_tight_layout_guide_002.png :alt: Title :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 58-65 Note that :func:`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 :rc:`figure.autolayout` to ``True``. When you have multiple subplots, often you see labels of different axes overlapping each other. .. GENERATED FROM PYTHON SOURCE LINES 65-74 .. code-block:: default 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) .. image:: /tutorials/intermediate/images/sphx_glr_tight_layout_guide_003.png :alt: Title, Title, Title, Title :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 75-77 :func:`~matplotlib.pyplot.tight_layout` will also adjust spacing between subplots to minimize the overlaps. .. GENERATED FROM PYTHON SOURCE LINES 77-85 .. code-block:: default 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() .. image:: /tutorials/intermediate/images/sphx_glr_tight_layout_guide_004.png :alt: Title, Title, Title, Title :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 86-90 :func:`~matplotlib.pyplot.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. .. GENERATED FROM PYTHON SOURCE LINES 90-98 .. code-block:: default 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) .. image:: /tutorials/intermediate/images/sphx_glr_tight_layout_guide_005.png :alt: Title, Title, Title, Title :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 99-103 :func:`~matplotlib.pyplot.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. .. GENERATED FROM PYTHON SOURCE LINES 103-117 .. code-block:: default plt.close('all') fig = plt.figure() ax1 = plt.subplot(221) ax2 = plt.subplot(223) ax3 = plt.subplot(122) example_plot(ax1) example_plot(ax2) example_plot(ax3) plt.tight_layout() .. image:: /tutorials/intermediate/images/sphx_glr_tight_layout_guide_006.png :alt: Title, Title, Title :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 118-121 It works with subplots created with :func:`~matplotlib.pyplot.subplot2grid`. In general, subplots created from the gridspec (:doc:`/tutorials/intermediate/gridspec`) will work. .. GENERATED FROM PYTHON SOURCE LINES 121-137 .. code-block:: default 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() .. image:: /tutorials/intermediate/images/sphx_glr_tight_layout_guide_007.png :alt: Title, Title, Title, Title :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 138-140 Although not thoroughly tested, it seems to work for subplots with aspect != "auto" (e.g., axes with images). .. GENERATED FROM PYTHON SOURCE LINES 140-151 .. code-block:: default arr = np.arange(100).reshape((10, 10)) plt.close('all') fig = plt.figure(figsize=(5, 4)) ax = plt.subplot(111) im = ax.imshow(arr, interpolation="none") plt.tight_layout() .. image:: /tutorials/intermediate/images/sphx_glr_tight_layout_guide_008.png :alt: tight layout guide :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 152-172 Caveats ======= * `~matplotlib.pyplot.tight_layout` considers all artists on the axes by default. To remove an artist from the layout calculation you can call `.Artist.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). .. GENERATED FROM PYTHON SOURCE LINES 172-187 .. code-block:: default import matplotlib.gridspec as gridspec plt.close('all') fig = plt.figure() gs1 = gridspec.GridSpec(2, 1) ax1 = fig.add_subplot(gs1[0]) ax2 = fig.add_subplot(gs1[1]) example_plot(ax1) example_plot(ax2) gs1.tight_layout(fig) .. image:: /tutorials/intermediate/images/sphx_glr_tight_layout_guide_009.png :alt: Title, Title :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 188-191 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). .. GENERATED FROM PYTHON SOURCE LINES 191-203 .. code-block:: default fig = plt.figure() gs1 = gridspec.GridSpec(2, 1) ax1 = fig.add_subplot(gs1[0]) ax2 = fig.add_subplot(gs1[1]) example_plot(ax1) example_plot(ax2) gs1.tight_layout(fig, rect=[0, 0, 0.5, 1]) .. image:: /tutorials/intermediate/images/sphx_glr_tight_layout_guide_010.png :alt: Title, Title :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 204-205 For example, this can be used for a figure with multiple gridspecs. .. GENERATED FROM PYTHON SOURCE LINES 205-237 .. code-block:: default fig = plt.figure() gs1 = gridspec.GridSpec(2, 1) ax1 = fig.add_subplot(gs1[0]) ax2 = fig.add_subplot(gs1[1]) example_plot(ax1) example_plot(ax2) gs1.tight_layout(fig, rect=[0, 0, 0.5, 1]) gs2 = gridspec.GridSpec(3, 1) for ss in gs2: ax = fig.add_subplot(ss) example_plot(ax) ax.set_title("") ax.set_xlabel("") ax.set_xlabel("x-label", fontsize=12) gs2.tight_layout(fig, rect=[0.5, 0, 1, 1], h_pad=0.5) # We may try to match the top and bottom of two grids :: top = min(gs1.top, gs2.top) bottom = max(gs1.bottom, gs2.bottom) gs1.update(top=top, bottom=bottom) gs2.update(top=top, bottom=bottom) plt.show() .. image:: /tutorials/intermediate/images/sphx_glr_tight_layout_guide_011.png :alt: Title, Title :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out Out: .. code-block:: none /build/matplotlib-eAPYn3/matplotlib-3.3.4/tutorials/intermediate/tight_layout_guide.py:227: UserWarning: This figure includes Axes that are not compatible with tight_layout, so results might be incorrect. gs2.tight_layout(fig, rect=[0.5, 0, 1, 1], h_pad=0.5) .. GENERATED FROM PYTHON SOURCE LINES 238-245 While this should be mostly good enough, adjusting top and bottom may require adjustment of hspace also. To update hspace & vspace, we call `.GridSpec.tight_layout` again with updated rect argument. Note that the rect argument specifies the area including the ticklabels, etc. Thus, we will increase the bottom (which is 0 for the normal case) by the difference between the *bottom* from above and the bottom of each gridspec. Same thing for the top. .. GENERATED FROM PYTHON SOURCE LINES 245-284 .. code-block:: default fig = plt.gcf() gs1 = gridspec.GridSpec(2, 1) ax1 = fig.add_subplot(gs1[0]) ax2 = fig.add_subplot(gs1[1]) example_plot(ax1) example_plot(ax2) gs1.tight_layout(fig, rect=[0, 0, 0.5, 1]) gs2 = gridspec.GridSpec(3, 1) for ss in gs2: ax = fig.add_subplot(ss) example_plot(ax) ax.set_title("") ax.set_xlabel("") ax.set_xlabel("x-label", fontsize=12) gs2.tight_layout(fig, rect=[0.5, 0, 1, 1], h_pad=0.5) top = min(gs1.top, gs2.top) bottom = max(gs1.bottom, gs2.bottom) gs1.update(top=top, bottom=bottom) gs2.update(top=top, bottom=bottom) top = min(gs1.top, gs2.top) bottom = max(gs1.bottom, gs2.bottom) gs1.tight_layout(fig, rect=[None, 0 + (bottom-gs1.bottom), 0.5, 1 - (gs1.top-top)]) gs2.tight_layout(fig, rect=[0.5, 0 + (bottom-gs2.bottom), None, 1 - (gs2.top-top)], h_pad=0.5) .. image:: /tutorials/intermediate/images/sphx_glr_tight_layout_guide_012.png :alt: Title, Title :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out Out: .. code-block:: none /build/matplotlib-eAPYn3/matplotlib-3.3.4/tutorials/intermediate/tight_layout_guide.py:267: UserWarning: This figure includes Axes that are not compatible with tight_layout, so results might be incorrect. gs2.tight_layout(fig, rect=[0.5, 0, 1, 1], h_pad=0.5) /build/matplotlib-eAPYn3/matplotlib-3.3.4/tutorials/intermediate/tight_layout_guide.py:278: UserWarning: This figure includes Axes that are not compatible with tight_layout, so results might be incorrect. gs1.tight_layout(fig, rect=[None, 0 + (bottom-gs1.bottom), /build/matplotlib-eAPYn3/matplotlib-3.3.4/tutorials/intermediate/tight_layout_guide.py:280: UserWarning: This figure includes Axes that are not compatible with tight_layout, so results might be incorrect. gs2.tight_layout(fig, rect=[0.5, 0 + (bottom-gs2.bottom), .. GENERATED FROM PYTHON SOURCE LINES 285-293 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 shring a bit to make room for the legend: .. GENERATED FROM PYTHON SOURCE LINES 293-300 .. code-block:: default fig, ax = plt.subplots(figsize=(4, 3)) lines = ax.plot(range(10), label='A simple plot') ax.legend(bbox_to_anchor=(0.7, 0.5), loc='center left',) fig.tight_layout() plt.show() .. image:: /tutorials/intermediate/images/sphx_glr_tight_layout_guide_013.png :alt: tight layout guide :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 301-305 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. .. GENERATED FROM PYTHON SOURCE LINES 305-313 .. code-block:: default fig, ax = plt.subplots(figsize=(4, 3)) lines = ax.plot(range(10), label='B simple plot') leg = ax.legend(bbox_to_anchor=(0.7, 0.5), loc='center left',) leg.set_in_layout(False) fig.tight_layout() plt.show() .. image:: /tutorials/intermediate/images/sphx_glr_tight_layout_guide_014.png :alt: tight layout guide :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 314-318 Use with AxesGrid1 ================== While limited, :mod:`mpl_toolkits.axes_grid1` is also supported. .. GENERATED FROM PYTHON SOURCE LINES 318-333 .. code-block:: default from mpl_toolkits.axes_grid1 import Grid plt.close('all') fig = plt.figure() grid = Grid(fig, rect=111, nrows_ncols=(2, 2), axes_pad=0.25, label_mode='L', ) for ax in grid: example_plot(ax) ax.title.set_visible(False) plt.tight_layout() .. image:: /tutorials/intermediate/images/sphx_glr_tight_layout_guide_015.png :alt: Title, Title, Title, Title :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 334-340 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. .. GENERATED FROM PYTHON SOURCE LINES 340-350 .. code-block:: default plt.close('all') arr = np.arange(100).reshape((10, 10)) fig = plt.figure(figsize=(4, 4)) im = plt.imshow(arr, interpolation="none") plt.colorbar(im) plt.tight_layout() .. image:: /tutorials/intermediate/images/sphx_glr_tight_layout_guide_016.png :alt: tight layout guide :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 351-353 Another option is to use AxesGrid1 toolkit to explicitly create an axes for colorbar. .. GENERATED FROM PYTHON SOURCE LINES 353-366 .. code-block:: default from mpl_toolkits.axes_grid1 import make_axes_locatable plt.close('all') arr = np.arange(100).reshape((10, 10)) fig = plt.figure(figsize=(4, 4)) im = plt.imshow(arr, interpolation="none") divider = make_axes_locatable(plt.gca()) cax = divider.append_axes("right", "5%", pad="3%") plt.colorbar(im, cax=cax) plt.tight_layout() .. image:: /tutorials/intermediate/images/sphx_glr_tight_layout_guide_017.png :alt: tight layout guide :class: sphx-glr-single-img .. rst-class:: sphx-glr-timing **Total running time of the script:** ( 0 minutes 11.849 seconds) .. _sphx_glr_download_tutorials_intermediate_tight_layout_guide.py: .. only :: html .. container:: sphx-glr-footer :class: sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: tight_layout_guide.py ` .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: tight_layout_guide.ipynb ` .. only:: html .. rst-class:: sphx-glr-signature Keywords: matplotlib code example, codex, python plot, pyplot `Gallery generated by Sphinx-Gallery `_