{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Contourf hatching\n\nDemo filled contour plots with hatched patterns.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\nimport numpy as np\n\n# invent some numbers, turning the x and y arrays into simple\n# 2d arrays, which make combining them together easier.\nx = np.linspace(-3, 5, 150).reshape(1, -1)\ny = np.linspace(-3, 5, 120).reshape(-1, 1)\nz = np.cos(x) + np.sin(y)\n\n# we no longer need x and y to be 2 dimensional, so flatten them.\nx, y = x.flatten(), y.flatten()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Plot 1: the simplest hatched plot with a colorbar\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "fig1, ax1 = plt.subplots()\ncs = ax1.contourf(x, y, z, hatches=['-', '/', '\\\\', '//'],\n cmap='gray', extend='both', alpha=0.5)\nfig1.colorbar(cs)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Plot 2: a plot of hatches without color with a legend\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "fig2, ax2 = plt.subplots()\nn_levels = 6\nax2.contour(x, y, z, n_levels, colors='black', linestyles='-')\ncs = ax2.contourf(x, y, z, n_levels, colors='none',\n hatches=['.', '/', '\\\\', None, '\\\\\\\\', '*'],\n extend='lower')\n\n# create a legend for the contour set\nartists, labels = cs.legend_elements(str_format='{:2.1f}'.format)\nax2.legend(artists, labels, handleheight=2, framealpha=1)\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.figure.Figure.colorbar` / `matplotlib.pyplot.colorbar`\n - `matplotlib.axes.Axes.legend` / `matplotlib.pyplot.legend`\n - `matplotlib.contour.ContourSet`\n - `matplotlib.contour.ContourSet.legend_elements`\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.13.2" } }, "nbformat": 4, "nbformat_minor": 0 }