
.. DO NOT EDIT.
.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY.
.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE:
.. "gallery/subplots_axes_and_figures/subplots_demo.py"
.. LINE NUMBERS ARE GIVEN BELOW.

.. only:: html

    .. meta::
        :keywords: codex

    .. note::
        :class: sphx-glr-download-link-note

        :ref:`Go to the end <sphx_glr_download_gallery_subplots_axes_and_figures_subplots_demo.py>`
        to download the full example code.

.. rst-class:: sphx-glr-example-title

.. _sphx_glr_gallery_subplots_axes_and_figures_subplots_demo.py:


===============================================
Create multiple subplots using ``plt.subplots``
===============================================

`.pyplot.subplots` creates a figure and a grid of subplots with a single call,
while providing reasonable control over how the individual plots are created.
For more advanced use cases you can use `.GridSpec` for a more general subplot
layout or `.Figure.add_subplot` for adding subplots at arbitrary locations
within the figure.

.. GENERATED FROM PYTHON SOURCE LINES 12-21

.. code-block:: Python



    import matplotlib.pyplot as plt
    import numpy as np

    # Some example data to display
    x = np.linspace(0, 2 * np.pi, 400)
    y = np.sin(x ** 2)


.. GENERATED FROM PYTHON SOURCE LINES 23-31

A figure with just one subplot
""""""""""""""""""""""""""""""

``subplots()`` without arguments returns a `.Figure` and a single
`~.axes.Axes`.

This is actually the simplest and recommended way of creating a single
Figure and Axes.

.. GENERATED FROM PYTHON SOURCE LINES 31-36

.. code-block:: Python


    fig, ax = plt.subplots()
    ax.plot(x, y)
    ax.set_title('A single plot')


.. GENERATED FROM PYTHON SOURCE LINES 37-45

Stacking subplots in one direction
""""""""""""""""""""""""""""""""""

The first two optional arguments of `.pyplot.subplots` define the number of
rows and columns of the subplot grid.

When stacking in one direction only, the returned ``axs`` is a 1D numpy array
containing the list of created Axes.

.. GENERATED FROM PYTHON SOURCE LINES 45-51

.. code-block:: Python


    fig, axs = plt.subplots(2)
    fig.suptitle('Vertically stacked subplots')
    axs[0].plot(x, y)
    axs[1].plot(x, -y)


.. GENERATED FROM PYTHON SOURCE LINES 52-55

If you are creating just a few Axes, it's handy to unpack them immediately to
dedicated variables for each Axes. That way, we can use ``ax1`` instead of
the more verbose ``axs[0]``.

.. GENERATED FROM PYTHON SOURCE LINES 55-61

.. code-block:: Python


    fig, (ax1, ax2) = plt.subplots(2)
    fig.suptitle('Vertically stacked subplots')
    ax1.plot(x, y)
    ax2.plot(x, -y)


.. GENERATED FROM PYTHON SOURCE LINES 62-64

To obtain side-by-side subplots, pass parameters ``1, 2`` for one row and two
columns.

.. GENERATED FROM PYTHON SOURCE LINES 64-70

.. code-block:: Python


    fig, (ax1, ax2) = plt.subplots(1, 2)
    fig.suptitle('Horizontally stacked subplots')
    ax1.plot(x, y)
    ax2.plot(x, -y)


.. GENERATED FROM PYTHON SOURCE LINES 71-78

Stacking subplots in two directions
"""""""""""""""""""""""""""""""""""

When stacking in two directions, the returned ``axs`` is a 2D NumPy array.

If you have to set parameters for each subplot it's handy to iterate over
all subplots in a 2D grid using ``for ax in axs.flat:``.

.. GENERATED FROM PYTHON SOURCE LINES 78-96

.. code-block:: Python


    fig, axs = plt.subplots(2, 2)
    axs[0, 0].plot(x, y)
    axs[0, 0].set_title('Axis [0, 0]')
    axs[0, 1].plot(x, y, 'tab:orange')
    axs[0, 1].set_title('Axis [0, 1]')
    axs[1, 0].plot(x, -y, 'tab:green')
    axs[1, 0].set_title('Axis [1, 0]')
    axs[1, 1].plot(x, -y, 'tab:red')
    axs[1, 1].set_title('Axis [1, 1]')

    for ax in axs.flat:
        ax.set(xlabel='x-label', ylabel='y-label')

    # Hide x labels and tick labels for top plots and y ticks for right plots.
    for ax in axs.flat:
        ax.label_outer()


.. GENERATED FROM PYTHON SOURCE LINES 97-99

You can use tuple-unpacking also in 2D to assign all subplots to dedicated
variables:

.. GENERATED FROM PYTHON SOURCE LINES 99-110

.. code-block:: Python


    fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
    fig.suptitle('Sharing x per column, y per row')
    ax1.plot(x, y)
    ax2.plot(x, y**2, 'tab:orange')
    ax3.plot(x, -y, 'tab:green')
    ax4.plot(x, -y**2, 'tab:red')

    for ax in fig.get_axes():
        ax.label_outer()


.. GENERATED FROM PYTHON SOURCE LINES 111-116

Sharing axes
""""""""""""

By default, each Axes is scaled individually. Thus, if the ranges are
different the tick values of the subplots do not align.

.. GENERATED FROM PYTHON SOURCE LINES 116-122

.. code-block:: Python


    fig, (ax1, ax2) = plt.subplots(2)
    fig.suptitle('Axes values are scaled individually by default')
    ax1.plot(x, y)
    ax2.plot(x + 1, -y)


.. GENERATED FROM PYTHON SOURCE LINES 123-124

You can use *sharex* or *sharey* to align the horizontal or vertical axis.

.. GENERATED FROM PYTHON SOURCE LINES 124-130

.. code-block:: Python


    fig, (ax1, ax2) = plt.subplots(2, sharex=True)
    fig.suptitle('Aligning x-axis using sharex')
    ax1.plot(x, y)
    ax2.plot(x + 1, -y)


.. GENERATED FROM PYTHON SOURCE LINES 131-134

Setting *sharex* or *sharey* to ``True`` enables global sharing across the
whole grid, i.e. also the y-axes of vertically stacked subplots have the
same scale when using ``sharey=True``.

.. GENERATED FROM PYTHON SOURCE LINES 134-141

.. code-block:: Python


    fig, axs = plt.subplots(3, sharex=True, sharey=True)
    fig.suptitle('Sharing both axes')
    axs[0].plot(x, y ** 2)
    axs[1].plot(x, 0.3 * y, 'o')
    axs[2].plot(x, y, '+')


.. GENERATED FROM PYTHON SOURCE LINES 142-153

For subplots that are sharing axes one set of tick labels is enough. Tick
labels of inner Axes are automatically removed by *sharex* and *sharey*.
Still there remains an unused empty space between the subplots.

To precisely control the positioning of the subplots, one can explicitly
create a `.GridSpec` with `.Figure.add_gridspec`, and then call its
`~.GridSpecBase.subplots` method.  For example, we can reduce the height
between vertical subplots using ``add_gridspec(hspace=0)``.

`.label_outer` is a handy method to remove labels and ticks from subplots
that are not at the edge of the grid.

.. GENERATED FROM PYTHON SOURCE LINES 153-166

.. code-block:: Python


    fig = plt.figure()
    gs = fig.add_gridspec(3, hspace=0)
    axs = gs.subplots(sharex=True, sharey=True)
    fig.suptitle('Sharing both axes')
    axs[0].plot(x, y ** 2)
    axs[1].plot(x, 0.3 * y, 'o')
    axs[2].plot(x, y, '+')

    # Hide x labels and tick labels for all but bottom plot.
    for ax in axs:
        ax.label_outer()


.. GENERATED FROM PYTHON SOURCE LINES 167-169

Apart from ``True`` and ``False``, both *sharex* and *sharey* accept the
values 'row' and 'col' to share the values only per row or column.

.. GENERATED FROM PYTHON SOURCE LINES 169-182

.. code-block:: Python


    fig = plt.figure()
    gs = fig.add_gridspec(2, 2, hspace=0, wspace=0)
    (ax1, ax2), (ax3, ax4) = gs.subplots(sharex='col', sharey='row')
    fig.suptitle('Sharing x per column, y per row')
    ax1.plot(x, y)
    ax2.plot(x, y**2, 'tab:orange')
    ax3.plot(x + 1, -y, 'tab:green')
    ax4.plot(x + 2, -y**2, 'tab:red')

    for ax in fig.get_axes():
        ax.label_outer()


.. GENERATED FROM PYTHON SOURCE LINES 183-186

If you want a more complex sharing structure, you can first create the
grid of Axes with no sharing, and then call `.axes.Axes.sharex` or
`.axes.Axes.sharey` to add sharing info a posteriori.

.. GENERATED FROM PYTHON SOURCE LINES 186-199

.. code-block:: Python


    fig, axs = plt.subplots(2, 2)
    axs[0, 0].plot(x, y)
    axs[0, 0].set_title("main")
    axs[1, 0].plot(x, y**2)
    axs[1, 0].set_title("shares x with main")
    axs[1, 0].sharex(axs[0, 0])
    axs[0, 1].plot(x + 1, y + 1)
    axs[0, 1].set_title("unrelated")
    axs[1, 1].plot(x + 2, y + 2)
    axs[1, 1].set_title("also unrelated")
    fig.tight_layout()


.. GENERATED FROM PYTHON SOURCE LINES 200-206

Polar Axes
""""""""""

The parameter *subplot_kw* of `.pyplot.subplots` controls the subplot
properties (see also `.Figure.add_subplot`). In particular, this can be used
to create a grid of polar Axes.

.. GENERATED FROM PYTHON SOURCE LINES 206-213

.. code-block:: Python


    fig, (ax1, ax2) = plt.subplots(1, 2, subplot_kw=dict(projection='polar'))
    ax1.plot(x, y)
    ax2.plot(x, y ** 2)

    plt.show()


.. GENERATED FROM PYTHON SOURCE LINES 214-223

.. tags::

   component: subplot,
   component: axes,
   component: axis
   plot-type: line,
   plot-type: polar
   level: beginner
   purpose: showcase


.. _sphx_glr_download_gallery_subplots_axes_and_figures_subplots_demo.py:

.. only:: html

  .. container:: sphx-glr-footer sphx-glr-footer-example

    .. container:: sphx-glr-download sphx-glr-download-jupyter

      :download:`Download Jupyter notebook: subplots_demo.ipynb <subplots_demo.ipynb>`

    .. container:: sphx-glr-download sphx-glr-download-python

      :download:`Download Python source code: subplots_demo.py <subplots_demo.py>`

    .. container:: sphx-glr-download sphx-glr-download-zip

      :download:`Download zipped: subplots_demo.zip <subplots_demo.zip>`


.. only:: html

 .. rst-class:: sphx-glr-signature

    `Gallery generated by Sphinx-Gallery <https://sphinx-gallery.github.io>`_
