{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n.. redirect-from:: /tutorials/intermediate/gridspec\n.. redirect-from:: /tutorials/intermediate/arranging_axes\n\n\n# Arranging multiple Axes in a Figure\n\nOften more than one Axes is wanted on a figure at a time, usually\norganized into a regular grid. Matplotlib has a variety of tools for\nworking with grids of Axes that have evolved over the history of the library.\nHere we will discuss the tools we think users should use most often, the tools\nthat underpin how Axes are organized, and mention some of the older tools.\n\n

Note

Matplotlib uses *Axes* to refer to the drawing area that contains\n data, x- and y-axis, ticks, labels, title, etc. See `figure_parts`\n for more details. Another term that is often used is \"subplot\", which\n refers to an Axes that is in a grid with other Axes objects.

\n\n## Overview\n\n### Create grid-shaped combinations of Axes\n\n`~matplotlib.pyplot.subplots`\n The primary function used to create figures and a grid of Axes. It\n creates and places all Axes on the figure at once, and returns an\n object array with handles for the Axes in the grid. See\n `.Figure.subplots`.\n\nor\n\n`~matplotlib.pyplot.subplot_mosaic`\n A simple way to create figures and a grid of Axes, with the added\n flexibility that Axes can also span rows or columns. The Axes are returned\n in a labelled dictionary instead of an array. See also\n `.Figure.subplot_mosaic` and\n `mosaic`.\n\nSometimes it is natural to have more than one distinct group of Axes grids,\nin which case Matplotlib has the concept of `.SubFigure`:\n\n`~matplotlib.figure.SubFigure`\n A virtual figure within a figure.\n\n### Underlying tools\n\nUnderlying these are the concept of a `~.gridspec.GridSpec` and\na `~.SubplotSpec`:\n\n`~matplotlib.gridspec.GridSpec`\n Specifies the geometry of the grid that a subplot will be\n placed. The number of rows and number of columns of the grid\n need to be set. Optionally, the subplot layout parameters\n (e.g., left, right, etc.) can be tuned.\n\n`~matplotlib.gridspec.SubplotSpec`\n Specifies the location of the subplot in the given `.GridSpec`.\n\n\n### Adding single Axes at a time\n\nThe above functions create all Axes in a single function call. It is also\npossible to add Axes one at a time, and this was originally how Matplotlib\nused to work. Doing so is generally less elegant and flexible, though\nsometimes useful for interactive work or to place an Axes in a custom\nlocation:\n\n`~matplotlib.figure.Figure.add_axes`\n Adds a single Axes at a location specified by\n ``[left, bottom, width, height]`` in fractions of figure width or height.\n\n`~matplotlib.pyplot.subplot` or `.Figure.add_subplot`\n Adds a single subplot on a figure, with 1-based indexing (inherited from\n Matlab). Columns and rows can be spanned by specifying a range of grid\n cells.\n\n`~matplotlib.pyplot.subplot2grid`\n Similar to `.pyplot.subplot`, but uses 0-based indexing and two-d python\n slicing to choose cells.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As a simple example of manually adding an Axes *ax*, lets add a 3 inch x 2 inch\nAxes to a 4 inch x 3 inch figure. Note that the location of the subplot is\ndefined as [left, bottom, width, height] in figure-normalized units:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\nimport numpy as np\n\nw, h = 4, 3\nmargin = 0.5\nfig = plt.figure(figsize=(w, h), facecolor='lightblue')\nax = fig.add_axes([margin / w, margin / h, (w - 2 * margin) / w,\n (h - 2 * margin) / h])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## High-level methods for making grids\n\n### Basic 2x2 grid\n\nWe can create a basic 2-by-2 grid of Axes using\n`~matplotlib.pyplot.subplots`. It returns a `~matplotlib.figure.Figure`\ninstance and an array of `~matplotlib.axes.Axes` objects. The Axes\nobjects can be used to access methods to place artists on the Axes; here\nwe use `~.Axes.annotate`, but other examples could be `~.Axes.plot`,\n`~.Axes.pcolormesh`, etc.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "fig, axs = plt.subplots(ncols=2, nrows=2, figsize=(5.5, 3.5),\n layout=\"constrained\")\n# add an artist, in this case a nice label in the middle...\nfor row in range(2):\n for col in range(2):\n axs[row, col].annotate(f'axs[{row}, {col}]', (0.5, 0.5),\n transform=axs[row, col].transAxes,\n ha='center', va='center', fontsize=18,\n color='darkgrey')\nfig.suptitle('plt.subplots()')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We will annotate a lot of Axes, so let's encapsulate the annotation, rather\nthan having that large piece of annotation code every time we need it:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def annotate_axes(ax, text, fontsize=18):\n ax.text(0.5, 0.5, text, transform=ax.transAxes,\n ha=\"center\", va=\"center\", fontsize=fontsize, color=\"darkgrey\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The same effect can be achieved with `~.pyplot.subplot_mosaic`,\nbut the return type is a dictionary instead of an array, where the user\ncan give the keys useful meanings. Here we provide two lists, each list\nrepresenting a row, and each element in the list a key representing the\ncolumn.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "fig, axd = plt.subplot_mosaic([['upper left', 'upper right'],\n ['lower left', 'lower right']],\n figsize=(5.5, 3.5), layout=\"constrained\")\nfor k, ax in axd.items():\n annotate_axes(ax, f'axd[{k!r}]', fontsize=14)\nfig.suptitle('plt.subplot_mosaic()')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Grids of fixed-aspect ratio Axes\n\nFixed-aspect ratio Axes are common for images or maps. However, they\npresent a challenge to layout because two sets of constraints are being\nimposed on the size of the Axes - that they fit in the figure and that they\nhave a set aspect ratio. This leads to large gaps between Axes by default:\n\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "fig, axs = plt.subplots(2, 2, layout=\"constrained\",\n figsize=(5.5, 3.5), facecolor='lightblue')\nfor ax in axs.flat:\n ax.set_aspect(1)\nfig.suptitle('Fixed aspect Axes')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "One way to address this is to change the aspect of the figure to be close\nto the aspect ratio of the Axes, however that requires trial and error.\nMatplotlib also supplies ``layout=\"compressed\"``, which will work with\nsimple grids to reduce the gaps between Axes. (The ``mpl_toolkits`` also\nprovides `~.mpl_toolkits.axes_grid1.axes_grid.ImageGrid` to accomplish\na similar effect, but with a non-standard Axes class).\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "fig, axs = plt.subplots(2, 2, layout=\"compressed\", figsize=(5.5, 3.5),\n facecolor='lightblue')\nfor ax in axs.flat:\n ax.set_aspect(1)\nfig.suptitle('Fixed aspect Axes: compressed')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Axes spanning rows or columns in a grid\n\nSometimes we want Axes to span rows or columns of the grid.\nThere are actually multiple ways to accomplish this, but the most\nconvenient is probably to use `~.pyplot.subplot_mosaic` by repeating one\nof the keys:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "fig, axd = plt.subplot_mosaic([['upper left', 'right'],\n ['lower left', 'right']],\n figsize=(5.5, 3.5), layout=\"constrained\")\nfor k, ax in axd.items():\n annotate_axes(ax, f'axd[{k!r}]', fontsize=14)\nfig.suptitle('plt.subplot_mosaic()')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "See below for the description of how to do the same thing using\n`~matplotlib.gridspec.GridSpec` or `~matplotlib.pyplot.subplot2grid`.\n\n### Variable widths or heights in a grid\n\nBoth `~.pyplot.subplots` and `~.pyplot.subplot_mosaic` allow the rows\nin the grid to be different heights, and the columns to be different\nwidths using the *gridspec_kw* keyword argument.\nSpacing parameters accepted by `~matplotlib.gridspec.GridSpec`\ncan be passed to `~matplotlib.pyplot.subplots` and\n`~matplotlib.pyplot.subplot_mosaic`:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "gs_kw = dict(width_ratios=[1.4, 1], height_ratios=[1, 2])\nfig, axd = plt.subplot_mosaic([['upper left', 'right'],\n ['lower left', 'right']],\n gridspec_kw=gs_kw, figsize=(5.5, 3.5),\n layout=\"constrained\")\nfor k, ax in axd.items():\n annotate_axes(ax, f'axd[{k!r}]', fontsize=14)\nfig.suptitle('plt.subplot_mosaic()')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n### Nested Axes layouts\n\nSometimes it is helpful to have two or more grids of Axes that\nmay not need to be related to one another. The most simple way to\naccomplish this is to use `.Figure.subfigures`. Note that the subfigure\nlayouts are independent, so the Axes spines in each subfigure are not\nnecessarily aligned. See below for a more verbose way to achieve the same\neffect with `~.gridspec.GridSpecFromSubplotSpec`.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "fig = plt.figure(layout=\"constrained\")\nsubfigs = fig.subfigures(1, 2, wspace=0.07, width_ratios=[1.5, 1.])\naxs0 = subfigs[0].subplots(2, 2)\nsubfigs[0].set_facecolor('lightblue')\nsubfigs[0].suptitle('subfigs[0]\\nLeft side')\nsubfigs[0].supxlabel('xlabel for subfigs[0]')\n\naxs1 = subfigs[1].subplots(3, 1)\nsubfigs[1].suptitle('subfigs[1]')\nsubfigs[1].supylabel('ylabel for subfigs[1]')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It is also possible to nest Axes using `~.pyplot.subplot_mosaic` using\nnested lists. This method does not use subfigures, like above, so lacks\nthe ability to add per-subfigure ``suptitle`` and ``supxlabel``, etc.\nRather it is a convenience wrapper around the `~.SubplotSpec.subgridspec`\nmethod described below.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "inner = [['innerA'],\n ['innerB']]\nouter = [['upper left', inner],\n ['lower left', 'lower right']]\n\nfig, axd = plt.subplot_mosaic(outer, layout=\"constrained\")\nfor k, ax in axd.items():\n annotate_axes(ax, f'axd[{k!r}]')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Low-level and advanced grid methods\n\nInternally, the arrangement of a grid of Axes is controlled by creating\ninstances of `~.GridSpec` and `~.SubplotSpec`. *GridSpec* defines a\n(possibly non-uniform) grid of cells. Indexing into the *GridSpec* returns\na SubplotSpec that covers one or more grid cells, and can be used to\nspecify the location of an Axes.\n\nThe following examples show how to use low-level methods to arrange Axes\nusing *GridSpec* objects.\n\n### Basic 2x2 grid\n\nWe can accomplish a 2x2 grid in the same manner as\n``plt.subplots(2, 2)``:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "fig = plt.figure(figsize=(5.5, 3.5), layout=\"constrained\")\nspec = fig.add_gridspec(ncols=2, nrows=2)\n\nax0 = fig.add_subplot(spec[0, 0])\nannotate_axes(ax0, 'ax0')\n\nax1 = fig.add_subplot(spec[0, 1])\nannotate_axes(ax1, 'ax1')\n\nax2 = fig.add_subplot(spec[1, 0])\nannotate_axes(ax2, 'ax2')\n\nax3 = fig.add_subplot(spec[1, 1])\nannotate_axes(ax3, 'ax3')\n\nfig.suptitle('Manually added subplots using add_gridspec')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Axes spanning rows or grids in a grid\n\nWe can index the *spec* array using [NumPy slice syntax](https://numpy.org/doc/stable/user/basics.indexing.html)\nand the new Axes will span the slice. This would be the same\nas ``fig, axd = plt.subplot_mosaic([['ax0', 'ax0'], ['ax1', 'ax2']], ...)``:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "fig = plt.figure(figsize=(5.5, 3.5), layout=\"constrained\")\nspec = fig.add_gridspec(2, 2)\n\nax0 = fig.add_subplot(spec[0, :])\nannotate_axes(ax0, 'ax0')\n\nax10 = fig.add_subplot(spec[1, 0])\nannotate_axes(ax10, 'ax10')\n\nax11 = fig.add_subplot(spec[1, 1])\nannotate_axes(ax11, 'ax11')\n\nfig.suptitle('Manually added subplots, spanning a column')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Manual adjustments to a *GridSpec* layout\n\nWhen a *GridSpec* is explicitly used, you can adjust the layout\nparameters of subplots that are created from the *GridSpec*. Note this\noption is not compatible with *constrained layout* or\n`.Figure.tight_layout` which both ignore *left* and *right* and adjust\nsubplot sizes to fill the figure. Usually such manual placement\nrequires iterations to make the Axes tick labels not overlap the Axes.\n\nThese spacing parameters can also be passed to `~.pyplot.subplots` and\n`~.pyplot.subplot_mosaic` as the *gridspec_kw* argument.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "fig = plt.figure(layout=None, facecolor='lightblue')\ngs = fig.add_gridspec(nrows=3, ncols=3, left=0.05, right=0.75,\n hspace=0.1, wspace=0.05)\nax0 = fig.add_subplot(gs[:-1, :])\nannotate_axes(ax0, 'ax0')\nax1 = fig.add_subplot(gs[-1, :-1])\nannotate_axes(ax1, 'ax1')\nax2 = fig.add_subplot(gs[-1, -1])\nannotate_axes(ax2, 'ax2')\nfig.suptitle('Manual gridspec with right=0.75')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Nested layouts with SubplotSpec\n\nYou can create nested layout similar to `~.Figure.subfigures` using\n`~.gridspec.SubplotSpec.subgridspec`. Here the Axes spines *are*\naligned.\n\nNote this is also available from the more verbose\n`.gridspec.GridSpecFromSubplotSpec`.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "fig = plt.figure(layout=\"constrained\")\ngs0 = fig.add_gridspec(1, 2)\n\ngs00 = gs0[0].subgridspec(2, 2)\ngs01 = gs0[1].subgridspec(3, 1)\n\nfor a in range(2):\n for b in range(2):\n ax = fig.add_subplot(gs00[a, b])\n annotate_axes(ax, f'axLeft[{a}, {b}]', fontsize=10)\n if a == 1 and b == 1:\n ax.set_xlabel('xlabel')\nfor a in range(3):\n ax = fig.add_subplot(gs01[a])\n annotate_axes(ax, f'axRight[{a}, {b}]')\n if a == 2:\n ax.set_ylabel('ylabel')\n\nfig.suptitle('nested gridspecs')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here's a more sophisticated example of nested *GridSpec*: We create an outer\n4x4 grid with each cell containing an inner 3x3 grid of Axes. We outline\nthe outer 4x4 grid by hiding appropriate spines in each of the inner 3x3\ngrids.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def squiggle_xy(a, b, c, d, i=np.arange(0.0, 2*np.pi, 0.05)):\n return np.sin(i*a)*np.cos(i*b), np.sin(i*c)*np.cos(i*d)\n\nfig = plt.figure(figsize=(8, 8), layout='constrained')\nouter_grid = fig.add_gridspec(4, 4, wspace=0, hspace=0)\n\nfor a in range(4):\n for b in range(4):\n # gridspec inside gridspec\n inner_grid = outer_grid[a, b].subgridspec(3, 3, wspace=0, hspace=0)\n axs = inner_grid.subplots() # Create all subplots for the inner grid.\n for (c, d), ax in np.ndenumerate(axs):\n ax.plot(*squiggle_xy(a + 1, b + 1, c + 1, d + 1))\n ax.set(xticks=[], yticks=[])\n\n# show only the outside spines\nfor ax in fig.get_axes():\n ss = ax.get_subplotspec()\n ax.spines.top.set_visible(ss.is_first_row())\n ax.spines.bottom.set_visible(ss.is_last_row())\n ax.spines.left.set_visible(ss.is_first_col())\n ax.spines.right.set_visible(ss.is_last_col())\n\nplt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## More reading\n\n- More details about `subplot mosaic `.\n- More details about `constrained layout\n `, used to align\n spacing in most of these examples.\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.pyplot.subplots`\n - `matplotlib.pyplot.subplot_mosaic`\n - `matplotlib.figure.Figure.add_gridspec`\n - `matplotlib.figure.Figure.add_subplot`\n - `matplotlib.gridspec.GridSpec`\n - `matplotlib.gridspec.SubplotSpec.subgridspec`\n - `matplotlib.gridspec.GridSpecFromSubplotSpec`\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 }