{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Placing images, preserving relative sizes\n\nBy default Matplotlib resamples images created with `~.Axes.imshow` to\nfit inside the parent `~.axes.Axes`. This can mean that images that have very\ndifferent original sizes can end up appearing similar in size.\n\nThis example shows how to keep the images the same relative size, or\nhow to make the images keep exactly the same pixels as the original data.\n\n## Preserving relative sizes\n\nBy default the two images are made a similar size, despite one being 1.5 times the width\nof the other:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\nimport numpy as np\n\nimport matplotlib.patches as mpatches\n\n# make the data:\nN = 450\nx = np.arange(N) / N\ny = np.arange(N) / N\n\nX, Y = np.meshgrid(x, y)\nR = np.sqrt(X**2 + Y**2)\nf0 = 5\nk = 100\na = np.sin(np.pi * 2 * (f0 * R + k * R**2 / 2))\nA = a[:100, :300]\nB = A[:40, :200]\n\n# default layout: both axes have the same size\nfig, axs = plt.subplots(1, 2, facecolor='aliceblue')\n\naxs[0].imshow(A, vmin=-1, vmax=1)\naxs[1].imshow(B, vmin=-1, vmax=1)\n\n\ndef annotate_rect(ax):\n # add a rectangle that is the size of the B matrix\n rect = mpatches.Rectangle((0, 0), 200, 40, linewidth=1,\n edgecolor='r', facecolor='none')\n ax.add_patch(rect)\n return rect\n\nannotate_rect(axs[0])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that both images have an aspect ratio of 1 (i.e. pixels are square), but\npixels sizes differ because the images are scaled to the same width.\n\nIf the size of the images are amenable, we can preserve the relative sizes of two\nimages by using either the *width_ratio* or *height_ratio* of the subplots. Which\none you use depends on the shape of the image and the size of the figure.\nWe can control the relative sizes using the *width_ratios* argument *if* the images\nare wider than they are tall and shown side by side, as is the case here.\n\nWhile we are making changes, let us also make the aspect ratio of the figure closer\nto the aspect ratio of the axes using *figsize* so that the figure does not have so\nmuch white space. Note that you could alternatively trim extra blank space when\nsaving a figure by passing ``bbox_inches=\"tight\"`` to `~.Figure.savefig`.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "fig, axs = plt.subplots(1, 2, width_ratios=[300/200, 1],\n figsize=(6.4, 2), facecolor='aliceblue')\n\naxs[0].imshow(A, vmin=-1, vmax=1)\nannotate_rect(axs[0])\n\naxs[1].imshow(B, vmin=-1, vmax=1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Given that the data subsample is in the upper left of the larger image,\nit might make sense if the top of the smaller Axes aligned with the top of the larger.\nThis can be done manually by using `~.Axes.set_anchor`, and using \"NW\" (for\nnorthwest).\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "fig, axs = plt.subplots(1, 2, width_ratios=[300/200, 1],\n figsize=(6.4, 2), facecolor='aliceblue')\n\naxs[0].imshow(A, vmin=-1, vmax=1)\nannotate_rect(axs[0])\n\naxs[0].set_anchor('NW')\naxs[1].imshow(B, vmin=-1, vmax=1)\naxs[1].set_anchor('NW')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Explicit placement\nThe above approach with adjusting ``figsize`` and ``width_ratios`` does\nnot generalize well, because it needs manual parameter tuning, and\npossibly even code changes to using ``height_ratios`` instead of\n``width_ratios`` depending on the aspects and layout of the images.\n\nWe can alternative calculate positions explicitly and place Axes at absolute\ncoordinates using `~.Figure.add_axes`. This takes the position in the form\n``[left bottom width height]`` and is in\n`figure coordinates `. In the following, we\ndetermine figure size and Axes positions so that one image data point\nis rendered exactly to one figure pixel.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "dpi = 100 # 100 pixels is one inch\n\n# All variables from here are in pixels:\nbuffer = 0.35 * dpi # pixels\n\n# Get the position of A axes\nleft = buffer\nbottom = buffer\nny, nx = np.shape(A)\nposA = [left, bottom, nx, ny]\n# we know this is tallest, so we can already get the fig height (in pixels)\nfig_height = bottom + ny + buffer\n\n# place the B axes to the right of the A axes\nleft = left + nx + buffer\n\nny, nx = np.shape(B)\n# align the bottom so that the top lines up with the top of the A axes:\nbottom = fig_height - buffer - ny\nposB = [left, bottom, nx, ny]\n\n# now we can get the fig width (in pixels)\nfig_width = left + nx + buffer\n\n# figsize must be in inches:\nfig = plt.figure(figsize=(fig_width / dpi, fig_height / dpi), facecolor='aliceblue')\n\n# the position posA must be normalized by the figure width and height:\nax = fig.add_axes((posA[0] / fig_width, posA[1] / fig_height,\n posA[2] / fig_width, posA[3] / fig_height))\nax.imshow(A, vmin=-1, vmax=1)\nannotate_rect(ax)\n\nax = fig.add_axes((posB[0] / fig_width, posB[1] / fig_height,\n posB[2] / fig_width, posB[3] / fig_height))\nax.imshow(B, vmin=-1, vmax=1)\nplt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Inspection of the image will show that it is exactly 3* 35 + 300 + 200 = 605\npixels wide, and 2 * 35 + 100 = 170 pixels high (or twice that if the 2x\nversion is used by the browser instead). The images should be rendered with\nexactly 1 pixel per data point (or four, if 2x).\n\n.. 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`\n - `matplotlib.figure.Figure.add_axes`\n\n.. tags::\n\n component: figure\n component: axes\n styling: position\n plot-type: image\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.12.15" } }, "nbformat": 4, "nbformat_minor": 0 }