{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n.. redirect-from:: /tutorials/provisional/mosaic\n.. redirect-from:: /gallery/subplots_axes_and_figures/mosaic\n\n\n# Complex and semantic figure composition (subplot_mosaic)\n\nLaying out Axes in a Figure in a non-uniform grid can be both tedious\nand verbose. For dense, even grids we have `.Figure.subplots` but for\nmore complex layouts, such as Axes that span multiple columns / rows\nof the layout or leave some areas of the Figure blank, you can use\n`.gridspec.GridSpec` (see `arranging_axes`) or\nmanually place your Axes. `.Figure.subplot_mosaic` aims to provide an\ninterface to visually lay out your Axes (as either ASCII art or nested\nlists) to streamline this process.\n\nThis interface naturally supports naming your Axes.\n`.Figure.subplot_mosaic` returns a dictionary keyed on the\nlabels used to lay out the Figure. By returning data structures with\nnames, it is easier to write plotting code that is independent of the\nFigure layout.\n\n\nThis is inspired by a [proposed MEP](https://github.com/matplotlib/matplotlib/pull/4384)_ and the\n[patchwork](https://github.com/thomasp85/patchwork)_ library for R.\nWhile we do not implement the operator overloading style, we do\nprovide a Pythonic API for specifying (nested) Axes layouts.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\nimport numpy as np\n\n\n# Helper function used for visualization in the following examples\ndef identify_axes(ax_dict, fontsize=48):\n \"\"\"\n Helper to identify the Axes in the examples below.\n\n Draws the label in a large font in the center of the Axes.\n\n Parameters\n ----------\n ax_dict : dict[str, Axes]\n Mapping between the title / label and the Axes.\n fontsize : int, optional\n How big the label should be.\n \"\"\"\n kw = dict(ha=\"center\", va=\"center\", fontsize=fontsize, color=\"darkgrey\")\n for k, ax in ax_dict.items():\n ax.text(0.5, 0.5, k, transform=ax.transAxes, **kw)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If we want a 2x2 grid we can use `.Figure.subplots` which returns a 2D array\nof `.axes.Axes` which we can index into to do our plotting.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "np.random.seed(19680801)\nhist_data = np.random.randn(1_500)\n\n\nfig = plt.figure(layout=\"constrained\")\nax_array = fig.subplots(2, 2, squeeze=False)\n\nax_array[0, 0].bar([\"a\", \"b\", \"c\"], [5, 7, 9])\nax_array[0, 1].plot([1, 2, 3])\nax_array[1, 0].hist(hist_data, bins=\"auto\")\nax_array[1, 1].imshow([[1, 2], [2, 1]])\n\nidentify_axes(\n {(j, k): a for j, r in enumerate(ax_array) for k, a in enumerate(r)},\n)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Using `.Figure.subplot_mosaic` we can produce the same mosaic but give the\nAxes semantic names\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "fig = plt.figure(layout=\"constrained\")\nax_dict = fig.subplot_mosaic(\n [\n [\"bar\", \"plot\"],\n [\"hist\", \"image\"],\n ],\n)\nax_dict[\"bar\"].bar([\"a\", \"b\", \"c\"], [5, 7, 9])\nax_dict[\"plot\"].plot([1, 2, 3])\nax_dict[\"hist\"].hist(hist_data)\nax_dict[\"image\"].imshow([[1, 2], [2, 1]])\nidentify_axes(ax_dict)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A key difference between `.Figure.subplots` and\n`.Figure.subplot_mosaic` is the return value. While the former\nreturns an array for index access, the latter returns a dictionary\nmapping the labels to the `.axes.Axes` instances created\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "print(ax_dict)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## String short-hand\n\nBy restricting our Axes labels to single characters we can\n\"draw\" the Axes we want as \"ASCII art\". The following\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "mosaic = \"\"\"\n AB\n CD\n \"\"\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "will give us 4 Axes laid out in a 2x2 grid and generates the same\nfigure mosaic as above (but now labeled with ``{\"A\", \"B\", \"C\",\n\"D\"}`` rather than ``{\"bar\", \"plot\", \"hist\", \"image\"}``).\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "fig = plt.figure(layout=\"constrained\")\nax_dict = fig.subplot_mosaic(mosaic)\nidentify_axes(ax_dict)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Alternatively, you can use the more compact string notation\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "mosaic = \"AB;CD\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "will give you the same composition, where the ``\";\"`` is used\nas the row separator instead of newline.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "fig = plt.figure(layout=\"constrained\")\nax_dict = fig.subplot_mosaic(mosaic)\nidentify_axes(ax_dict)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Axes spanning multiple rows/columns\n\nSomething we can do with `.Figure.subplot_mosaic`, that we cannot\ndo with `.Figure.subplots`, is to specify that an Axes should span\nseveral rows or columns.\n\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If we want to re-arrange our four Axes to have ``\"C\"`` be a horizontal\nspan on the bottom and ``\"D\"`` be a vertical span on the right we would do\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "axd = plt.figure(layout=\"constrained\").subplot_mosaic(\n \"\"\"\n ABD\n CCD\n \"\"\"\n)\nidentify_axes(axd)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If we do not want to fill in all the spaces in the Figure with Axes,\nwe can specify some spaces in the grid to be blank\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "axd = plt.figure(layout=\"constrained\").subplot_mosaic(\n \"\"\"\n A.C\n BBB\n .D.\n \"\"\"\n)\nidentify_axes(axd)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If we prefer to use another character (rather than a period ``\".\"``)\nto mark the empty space, we can use *empty_sentinel* to specify the\ncharacter to use.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "axd = plt.figure(layout=\"constrained\").subplot_mosaic(\n \"\"\"\n aX\n Xb\n \"\"\",\n empty_sentinel=\"X\",\n)\nidentify_axes(axd)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Internally there is no meaning attached to the letters we use, any\nUnicode code point is valid!\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "axd = plt.figure(layout=\"constrained\").subplot_mosaic(\n \"\"\"\u03b1\u0431\n \u211d\u2622\"\"\"\n)\nidentify_axes(axd)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It is not recommended to use white space as either a label or an\nempty sentinel with the string shorthand because it may be stripped\nwhile processing the input.\n\n## Controlling mosaic creation\n\nThis feature is built on top of `.gridspec` and you can pass the\nkeyword arguments through to the underlying `.gridspec.GridSpec`\n(the same as `.Figure.subplots`).\n\nIn this case we want to use the input to specify the arrangement,\nbut set the relative widths of the rows / columns. For convenience,\n`.gridspec.GridSpec`'s *height_ratios* and *width_ratios* are exposed in the\n`.Figure.subplot_mosaic` calling sequence.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "axd = plt.figure(layout=\"constrained\").subplot_mosaic(\n \"\"\"\n .a.\n bAc\n .d.\n \"\"\",\n # set the height ratios between the rows\n height_ratios=[1, 3.5, 1],\n # set the width ratios between the columns\n width_ratios=[1, 3.5, 1],\n)\nidentify_axes(axd)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Other `.gridspec.GridSpec` keywords can be passed via *gridspec_kw*. For\nexample, use the {*left*, *right*, *bottom*, *top*} keyword arguments to\nposition the overall mosaic to put multiple versions of the same\nmosaic in a figure.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "mosaic = \"\"\"AA\n BC\"\"\"\nfig = plt.figure()\naxd = fig.subplot_mosaic(\n mosaic,\n gridspec_kw={\n \"bottom\": 0.25,\n \"top\": 0.95,\n \"left\": 0.1,\n \"right\": 0.5,\n \"wspace\": 0.5,\n \"hspace\": 0.5,\n },\n)\nidentify_axes(axd)\n\naxd = fig.subplot_mosaic(\n mosaic,\n gridspec_kw={\n \"bottom\": 0.05,\n \"top\": 0.75,\n \"left\": 0.6,\n \"right\": 0.95,\n \"wspace\": 0.5,\n \"hspace\": 0.5,\n },\n)\nidentify_axes(axd)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Alternatively, you can use the sub-Figure functionality:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "mosaic = \"\"\"AA\n BC\"\"\"\nfig = plt.figure(layout=\"constrained\")\nleft, right = fig.subfigures(nrows=1, ncols=2)\naxd = left.subplot_mosaic(mosaic)\nidentify_axes(axd)\n\naxd = right.subplot_mosaic(mosaic)\nidentify_axes(axd)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Controlling subplot creation\n\nWe can also pass through arguments used to create the subplots\n(again, the same as `.Figure.subplots`) which will apply to all\nof the Axes created.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "axd = plt.figure(layout=\"constrained\").subplot_mosaic(\n \"AB\", subplot_kw={\"projection\": \"polar\"}\n)\nidentify_axes(axd)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Per-Axes subplot keyword arguments\n\nIf you need to control the parameters passed to each subplot individually use\n*per_subplot_kw* to pass a mapping between the Axes identifiers (or\ntuples of Axes identifiers) to dictionaries of keywords to be passed.\n\n.. versionadded:: 3.7\n\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "fig, axd = plt.subplot_mosaic(\n \"AB;CD\",\n per_subplot_kw={\n \"A\": {\"projection\": \"polar\"},\n (\"C\", \"D\"): {\"xscale\": \"log\"}\n },\n)\nidentify_axes(axd)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If the layout is specified with the string short-hand, then we know the\nAxes labels will be one character and can unambiguously interpret longer\nstrings in *per_subplot_kw* to specify a set of Axes to apply the\nkeywords to:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "fig, axd = plt.subplot_mosaic(\n \"AB;CD\",\n per_subplot_kw={\n \"AD\": {\"projection\": \"polar\"},\n \"BC\": {\"facecolor\": \".9\"}\n },\n)\nidentify_axes(axd)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If *subplot_kw* and *per_subplot_kw* are used together, then they are\nmerged with *per_subplot_kw* taking priority:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "axd = plt.figure(layout=\"constrained\").subplot_mosaic(\n \"AB;CD\",\n subplot_kw={\"facecolor\": \"xkcd:tangerine\"},\n per_subplot_kw={\n \"B\": {\"facecolor\": \"xkcd:water blue\"},\n \"D\": {\"projection\": \"polar\", \"facecolor\": \"w\"},\n }\n)\nidentify_axes(axd)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Nested list input\n\nEverything we can do with the string shorthand we can also do when\npassing in a list (internally we convert the string shorthand to a nested\nlist), for example using spans, blanks, and *gridspec_kw*:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "axd = plt.figure(layout=\"constrained\").subplot_mosaic(\n [\n [\"main\", \"zoom\"],\n [\"main\", \"BLANK\"],\n ],\n empty_sentinel=\"BLANK\",\n width_ratios=[2, 1],\n)\nidentify_axes(axd)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In addition, using the list input we can specify nested mosaics. Any element\nof the inner list can be another set of nested lists:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "inner = [\n [\"inner A\"],\n [\"inner B\"],\n]\n\nouter_nested_mosaic = [\n [\"main\", inner],\n [\"bottom\", \"bottom\"],\n]\naxd = plt.figure(layout=\"constrained\").subplot_mosaic(\n outer_nested_mosaic, empty_sentinel=None\n)\nidentify_axes(axd, fontsize=36)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can also pass in a 2D NumPy array to do things like\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "mosaic = np.zeros((4, 4), dtype=int)\nfor j in range(4):\n mosaic[j, j] = j + 1\naxd = plt.figure(layout=\"constrained\").subplot_mosaic(\n mosaic,\n empty_sentinel=0,\n)\nidentify_axes(axd)" ] } ], "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 }