
.. DO NOT EDIT.
.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY.
.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE:
.. "gallery/images_contours_and_fields/contourf_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_images_contours_and_fields_contourf_demo.py>`
        to download the full example code.

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

.. _sphx_glr_gallery_images_contours_and_fields_contourf_demo.py:


=============
Contourf demo
=============

How to use the `.axes.Axes.contourf` method to create filled contour plots.

.. GENERATED FROM PYTHON SOURCE LINES 8-34

.. code-block:: Python

    import matplotlib.pyplot as plt
    import numpy as np

    delta = 0.025

    x = y = np.arange(-3.0, 3.01, delta)
    X, Y = np.meshgrid(x, y)
    Z1 = np.exp(-X**2 - Y**2)
    Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
    Z = (Z1 - Z2) * 2

    nr, nc = Z.shape

    # put NaNs in one corner:
    Z[-nr // 6:, -nc // 6:] = np.nan
    # contourf will convert these to masked


    Z = np.ma.array(Z)
    # mask another corner:
    Z[:nr // 6, :nc // 6] = np.ma.masked

    # mask a circle in the middle:
    interior = np.sqrt(X**2 + Y**2) < 0.5
    Z[interior] = np.ma.masked








.. GENERATED FROM PYTHON SOURCE LINES 35-40

Automatic contour levels
------------------------
We are using automatic selection of contour levels; this is usually not such
a good idea, because they don't occur on nice boundaries, but we do it here
for purposes of illustration.

.. GENERATED FROM PYTHON SOURCE LINES 40-61

.. code-block:: Python


    fig1, ax2 = plt.subplots(layout='constrained')
    CS = ax2.contourf(X, Y, Z, 10, cmap=plt.cm.bone)

    # Note that in the following, we explicitly pass in a subset of the contour
    # levels used for the filled contours.  Alternatively, we could pass in
    # additional levels to provide extra resolution, or leave out the *levels*
    # keyword argument to use all of the original levels.

    CS2 = ax2.contour(CS, levels=CS.levels[::2], colors='r')

    ax2.set_title('Nonsense (3 masked regions)')
    ax2.set_xlabel('word length anomaly')
    ax2.set_ylabel('sentence length anomaly')

    # Make a colorbar for the ContourSet returned by the contourf call.
    cbar = fig1.colorbar(CS)
    cbar.ax.set_ylabel('verbosity coefficient')
    # Add the contour line levels to the colorbar
    cbar.add_lines(CS2)




.. image-sg:: /gallery/images_contours_and_fields/images/sphx_glr_contourf_demo_001.png
   :alt: Nonsense (3 masked regions)
   :srcset: /gallery/images_contours_and_fields/images/sphx_glr_contourf_demo_001.png, /gallery/images_contours_and_fields/images/sphx_glr_contourf_demo_001_2_00x.png 2.00x
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 62-66

Explicit contour levels
-----------------------
Now make a contour plot with the levels specified, and with the colormap
generated automatically from a list of colors.

.. GENERATED FROM PYTHON SOURCE LINES 66-84

.. code-block:: Python


    fig2, ax2 = plt.subplots(layout='constrained')
    levels = [-1.5, -1, -0.5, 0, 0.5, 1]
    CS3 = ax2.contourf(X, Y, Z, levels, colors=('r', 'g', 'b'), extend='both')
    # Our data range extends outside the range of levels; make
    # data below the lowest contour level yellow, and above the
    # highest level cyan:
    CS3.cmap.set_under('yellow')
    CS3.cmap.set_over('cyan')

    CS4 = ax2.contour(X, Y, Z, levels, colors=('k',), linewidths=(3,))
    ax2.set_title('Listed colors (3 masked regions)')
    ax2.clabel(CS4, fmt='%2.1f', colors='w', fontsize=14)

    # Notice that the colorbar gets all the information it
    # needs from the ContourSet object, CS3.
    fig2.colorbar(CS3)




.. image-sg:: /gallery/images_contours_and_fields/images/sphx_glr_contourf_demo_002.png
   :alt: Listed colors (3 masked regions)
   :srcset: /gallery/images_contours_and_fields/images/sphx_glr_contourf_demo_002.png, /gallery/images_contours_and_fields/images/sphx_glr_contourf_demo_002_2_00x.png 2.00x
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 85-88

Extension settings
------------------
Illustrate all 4 possible "extend" settings:

.. GENERATED FROM PYTHON SOURCE LINES 88-106

.. code-block:: Python

    extends = ["neither", "both", "min", "max"]
    cmap = plt.colormaps["winter"].with_extremes(under="magenta", over="yellow")
    # Note: contouring simply excludes masked or nan regions, so
    # instead of using the "bad" colormap value for them, it draws
    # nothing at all in them.  Therefore, the following would have
    # no effect:
    # cmap.set_bad("red")

    fig, axs = plt.subplots(2, 2, layout="constrained")

    for ax, extend in zip(axs.flat, extends):
        cs = ax.contourf(X, Y, Z, levels, cmap=cmap, extend=extend)
        fig.colorbar(cs, ax=ax, shrink=0.9)
        ax.set_title("extend = %s" % extend)
        ax.locator_params(nbins=4)

    plt.show()




.. image-sg:: /gallery/images_contours_and_fields/images/sphx_glr_contourf_demo_003.png
   :alt: extend = neither, extend = both, extend = min, extend = max
   :srcset: /gallery/images_contours_and_fields/images/sphx_glr_contourf_demo_003.png, /gallery/images_contours_and_fields/images/sphx_glr_contourf_demo_003_2_00x.png 2.00x
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 107-110

Orient contour plots using the origin keyword
---------------------------------------------
This code demonstrates orienting contour plot data using the "origin" keyword

.. GENERATED FROM PYTHON SOURCE LINES 110-124

.. code-block:: Python


    x = np.arange(1, 10)
    y = x.reshape(-1, 1)
    h = x * y

    fig, (ax1, ax2) = plt.subplots(ncols=2)

    ax1.set_title("origin='upper'")
    ax2.set_title("origin='lower'")
    ax1.contourf(h, levels=np.arange(5, 70, 5), extend='both', origin="upper")
    ax2.contourf(h, levels=np.arange(5, 70, 5), extend='both', origin="lower")

    plt.show()




.. image-sg:: /gallery/images_contours_and_fields/images/sphx_glr_contourf_demo_004.png
   :alt: origin='upper', origin='lower'
   :srcset: /gallery/images_contours_and_fields/images/sphx_glr_contourf_demo_004.png, /gallery/images_contours_and_fields/images/sphx_glr_contourf_demo_004_2_00x.png 2.00x
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 125-138

.. admonition:: References

   The use of the following functions, methods, classes and modules is shown
   in this example:

   - `matplotlib.axes.Axes.contour` / `matplotlib.pyplot.contour`
   - `matplotlib.axes.Axes.contourf` / `matplotlib.pyplot.contourf`
   - `matplotlib.axes.Axes.clabel` / `matplotlib.pyplot.clabel`
   - `matplotlib.figure.Figure.colorbar` / `matplotlib.pyplot.colorbar`
   - `matplotlib.colors.Colormap`
   - `matplotlib.colors.Colormap.set_bad`
   - `matplotlib.colors.Colormap.set_under`
   - `matplotlib.colors.Colormap.set_over`


.. rst-class:: sphx-glr-timing

   **Total running time of the script:** (0 minutes 1.515 seconds)


.. _sphx_glr_download_gallery_images_contours_and_fields_contourf_demo.py:

.. only:: html

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

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

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

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

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

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

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


.. only:: html

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

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