{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Contourf demo\n\nHow to use the `.axes.Axes.contourf` method to create filled contour plots.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\nimport numpy as np\n\ndelta = 0.025\n\nx = y = np.arange(-3.0, 3.01, delta)\nX, Y = np.meshgrid(x, y)\nZ1 = np.exp(-X**2 - Y**2)\nZ2 = np.exp(-(X - 1)**2 - (Y - 1)**2)\nZ = (Z1 - Z2) * 2\n\nnr, nc = Z.shape\n\n# put NaNs in one corner:\nZ[-nr // 6:, -nc // 6:] = np.nan\n# contourf will convert these to masked\n\n\nZ = np.ma.array(Z)\n# mask another corner:\nZ[:nr // 6, :nc // 6] = np.ma.masked\n\n# mask a circle in the middle:\ninterior = np.sqrt(X**2 + Y**2) < 0.5\nZ[interior] = np.ma.masked"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Automatic contour levels\nWe are using automatic selection of contour levels; this is usually not such\na good idea, because they don't occur on nice boundaries, but we do it here\nfor purposes of illustration.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "fig1, ax2 = plt.subplots(layout='constrained')\nCS = ax2.contourf(X, Y, Z, 10, cmap=\"bone\")\n\n# Note that in the following, we explicitly pass in a subset of the contour\n# levels used for the filled contours.  Alternatively, we could pass in\n# additional levels to provide extra resolution, or leave out the *levels*\n# keyword argument to use all of the original levels.\n\nCS2 = ax2.contour(CS, levels=CS.levels[::2], colors='r')\n\nax2.set_title('Nonsense (3 masked regions)')\nax2.set_xlabel('word length anomaly')\nax2.set_ylabel('sentence length anomaly')\n\n# Make a colorbar for the ContourSet returned by the contourf call.\ncbar = fig1.colorbar(CS)\ncbar.ax.set_ylabel('verbosity coefficient')\n# Add the contour line levels to the colorbar\ncbar.add_lines(CS2)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Explicit contour levels\nNow make a contour plot with the levels specified, and with the colormap\ngenerated automatically from a list of colors.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "fig2, ax2 = plt.subplots(layout='constrained')\nlevels = [-1.5, -1, -0.5, 0, 0.5, 1]\nCS3 = ax2.contourf(X, Y, Z, levels, colors=('r', 'g', 'b'), extend='both')\n# Our data range extends outside the range of levels; make\n# data below the lowest contour level yellow, and above the\n# highest level cyan:\nCS3.cmap.set_under('yellow')\nCS3.cmap.set_over('cyan')\n\nCS4 = ax2.contour(X, Y, Z, levels, colors=('k',), linewidths=(3,))\nax2.set_title('Listed colors (3 masked regions)')\nax2.clabel(CS4, fmt='%2.1f', colors='w', fontsize=14)\n\n# Notice that the colorbar gets all the information it\n# needs from the ContourSet object, CS3.\nfig2.colorbar(CS3)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Extension settings\nIllustrate all 4 possible \"extend\" settings:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "extends = [\"neither\", \"both\", \"min\", \"max\"]\ncmap = plt.colormaps[\"winter\"].with_extremes(under=\"magenta\", over=\"yellow\")\n# Note: contouring simply excludes masked or nan regions, so\n# instead of using the \"bad\" colormap value for them, it draws\n# nothing at all in them.  Therefore, the following would have\n# no effect:\n# cmap.set_bad(\"red\")\n\nfig, axs = plt.subplots(2, 2, layout=\"constrained\")\n\nfor ax, extend in zip(axs.flat, extends):\n    cs = ax.contourf(X, Y, Z, levels, cmap=cmap, extend=extend)\n    fig.colorbar(cs, ax=ax, shrink=0.9)\n    ax.set_title(\"extend = %s\" % extend)\n    ax.locator_params(nbins=4)\n\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Orient contour plots using the origin keyword\nThis code demonstrates orienting contour plot data using the \"origin\" keyword\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "x = np.arange(1, 10)\ny = x.reshape(-1, 1)\nh = x * y\n\nfig, (ax1, ax2) = plt.subplots(ncols=2)\n\nax1.set_title(\"origin='upper'\")\nax2.set_title(\"origin='lower'\")\nax1.contourf(h, levels=np.arange(5, 70, 5), extend='both', origin=\"upper\")\nax2.contourf(h, levels=np.arange(5, 70, 5), extend='both', origin=\"lower\")\n\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        ".. admonition:: References\n\n   The use of the following functions, methods, classes and modules is shown\n   in this example:\n\n   - `matplotlib.axes.Axes.contour` / `matplotlib.pyplot.contour`\n   - `matplotlib.axes.Axes.contourf` / `matplotlib.pyplot.contourf`\n   - `matplotlib.axes.Axes.clabel` / `matplotlib.pyplot.clabel`\n   - `matplotlib.figure.Figure.colorbar` / `matplotlib.pyplot.colorbar`\n   - `matplotlib.colors.Colormap`\n   - `matplotlib.colors.Colormap.set_bad`\n   - `matplotlib.colors.Colormap.set_under`\n   - `matplotlib.colors.Colormap.set_over`\n\n"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.14.6"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}