{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Many ways to plot images\n\nThe most common way to plot images in Matplotlib is with\n`~.axes.Axes.imshow`. The following examples demonstrate much of the\nfunctionality of imshow and the many images you can create.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\nimport numpy as np\n\nimport matplotlib.cbook as cbook\nimport matplotlib.cm as cm\nfrom matplotlib.patches import PathPatch\nfrom matplotlib.path import Path\n\n# Fixing random state for reproducibility\nnp.random.seed(19680801)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "First we'll generate a simple bivariate normal distribution.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "delta = 0.025\nx = y = np.arange(-3.0, 3.0, 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\nfig, ax = plt.subplots()\nim = ax.imshow(Z, interpolation='bilinear', cmap=cm.RdYlGn,\n origin='lower', extent=[-3, 3, -3, 3],\n vmax=abs(Z).max(), vmin=-abs(Z).max())\n\nplt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It is also possible to show images of pictures.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# A sample image\nwith cbook.get_sample_data('grace_hopper.jpg') as image_file:\n image = plt.imread(image_file)\n\n# And another image, using 256x256 16-bit integers.\nw, h = 256, 256\nwith cbook.get_sample_data('s1045.ima.gz') as datafile:\n s = datafile.read()\nA = np.frombuffer(s, np.uint16).astype(float).reshape((w, h))\nextent = (0, 25, 0, 25)\n\nfig, ax = plt.subplot_mosaic([\n ['hopper', 'mri']\n], figsize=(7, 3.5))\n\nax['hopper'].imshow(image)\nax['hopper'].axis('off') # clear x-axis and y-axis\n\nim = ax['mri'].imshow(A, cmap=plt.cm.hot, origin='upper', extent=extent)\n\nmarkers = [(15.9, 14.5), (16.8, 15)]\nx, y = zip(*markers)\nax['mri'].plot(x, y, 'o')\n\nax['mri'].set_title('MRI')\n\nplt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Interpolating images\n\nIt is also possible to interpolate images before displaying them. Be careful,\nas this may manipulate the way your data looks, but it can be helpful for\nachieving the look you want. Below we'll display the same (small) array,\ninterpolated with three different interpolation methods.\n\nThe center of the pixel at A[i, j] is plotted at (i+0.5, i+0.5). If you\nare using interpolation='nearest', the region bounded by (i, j) and\n(i+1, j+1) will have the same color. If you are using interpolation,\nthe pixel center will have the same color as it does with nearest, but\nother pixels will be interpolated between the neighboring pixels.\n\nTo prevent edge effects when doing interpolation, Matplotlib pads the input\narray with identical pixels around the edge: if you have a 5x5 array with\ncolors a-y as below::\n\n a b c d e\n f g h i j\n k l m n o\n p q r s t\n u v w x y\n\nMatplotlib computes the interpolation and resizing on the padded array ::\n\n a a b c d e e\n a a b c d e e\n f f g h i j j\n k k l m n o o\n p p q r s t t\n o u v w x y y\n o u v w x y y\n\nand then extracts the central region of the result. (Extremely old versions\nof Matplotlib (<0.63) did not pad the array, but instead adjusted the view\nlimits to hide the affected edge areas.)\n\nThis approach allows plotting the full extent of an array without\nedge effects, and for example to layer multiple images of different\nsizes over one another with different interpolation methods -- see\n:doc:`/gallery/images_contours_and_fields/layer_images`. It also implies\na performance hit, as this new temporary, padded array must be created.\nSophisticated interpolation also implies a performance hit; for maximal\nperformance or very large images, interpolation='nearest' is suggested.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "A = np.random.rand(5, 5)\n\nfig, axs = plt.subplots(1, 3, figsize=(10, 3))\nfor ax, interp in zip(axs, ['nearest', 'bilinear', 'bicubic']):\n ax.imshow(A, interpolation=interp)\n ax.set_title(interp.capitalize())\n ax.grid(True)\n\nplt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can specify whether images should be plotted with the array origin\nx[0, 0] in the upper left or lower right by using the origin parameter.\nYou can also control the default setting image.origin in your\n`matplotlibrc file `. For more on\nthis topic see the `complete guide on origin and extent\n`.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "x = np.arange(120).reshape((10, 12))\n\ninterp = 'bilinear'\nfig, axs = plt.subplots(nrows=2, sharex=True, figsize=(3, 5))\naxs[0].set_title('blue should be up')\naxs[0].imshow(x, origin='upper', interpolation=interp)\n\naxs[1].set_title('blue should be down')\naxs[1].imshow(x, origin='lower', interpolation=interp)\nplt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Finally, we'll show an image using a clip path.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "delta = 0.025\nx = y = np.arange(-3.0, 3.0, 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\npath = Path([[0, 1], [1, 0], [0, -1], [-1, 0], [0, 1]])\npatch = PathPatch(path, facecolor='none')\n\nfig, ax = plt.subplots()\nax.add_patch(patch)\n\nim = ax.imshow(Z, interpolation='bilinear', cmap=cm.gray,\n origin='lower', extent=[-3, 3, -3, 3],\n clip_path=patch, clip_on=True)\nim.set_clip_path(patch)\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.imshow` / `matplotlib.pyplot.imshow`\n - `matplotlib.artist.Artist.set_clip_path`\n - `matplotlib.patches.PathPatch`\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 }