{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n.. redirect-from:: /tutorials/intermediate/legend_guide\n\n\n# Legend guide\n\n.. currentmodule:: matplotlib.pyplot\n\nThis legend guide extends the `~.Axes.legend` docstring -\nplease read it before proceeding with this guide.\n\nThis guide makes use of some common terms, which are documented here for\nclarity:\n\n.. glossary::\n\n legend entry\n A legend is made up of one or more legend entries. An entry is made up\n of exactly one key and one label.\n\n legend key\n The colored/patterned marker to the left of each legend label.\n\n legend label\n The text which describes the handle represented by the key.\n\n legend handle\n The original object which is used to generate an appropriate entry in\n the legend.\n\n\n## Controlling the legend entries\n\nCalling :func:`legend` with no arguments automatically fetches the legend\nhandles and their associated labels. This functionality is equivalent to::\n\n handles, labels = ax.get_legend_handles_labels()\n ax.legend(handles, labels)\n\nThe :meth:`~matplotlib.axes.Axes.get_legend_handles_labels` function returns\na list of handles/artists which exist on the Axes which can be used to\ngenerate entries for the resulting legend - it is worth noting however that\nnot all artists can be added to a legend, at which point a \"proxy\" will have\nto be created (see `proxy_legend_handles` for further details).\n\n

Note

Artists with an empty string as label or with a label starting with an\n underscore, \"_\", will be ignored.

\n\nFor full control of what is being added to the legend, it is common to pass\nthe appropriate handles directly to :func:`legend`::\n\n fig, ax = plt.subplots()\n line_up, = ax.plot([1, 2, 3], label='Line 2')\n line_down, = ax.plot([3, 2, 1], label='Line 1')\n ax.legend(handles=[line_up, line_down])\n\n### Renaming legend entries\n\nWhen the labels cannot directly be set on the handles, they can be directly passed to\n`.Axes.legend`::\n\n fig, ax = plt.subplots()\n line_up, = ax.plot([1, 2, 3], label='Line 2')\n line_down, = ax.plot([3, 2, 1], label='Line 1')\n ax.legend([line_up, line_down], ['Line Up', 'Line Down'])\n\n\nIf the handles are not directly accessible, for example when using some\n[Third-party packages](https://matplotlib.org/mpl-third-party/), they can be accessed\nvia `.Axes.get_legend_handles_labels`. Here we use a dictionary to rename existing\nlabels::\n\n my_map = {'Line Up':'Up', 'Line Down':'Down'}\n\n handles, labels = ax.get_legend_handles_labels()\n ax.legend(handles, [my_map[l] for l in labels])\n\n\n\n## Creating artists specifically for adding to the legend (aka. Proxy artists)\n\nNot all handles can be turned into legend entries automatically,\nso it is often necessary to create an artist which *can*. Legend handles\ndon't have to exist on the Figure or Axes in order to be used.\n\nSuppose we wanted to create a legend which has an entry for some data which\nis represented by a red color:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n\nimport matplotlib.patches as mpatches\n\nfig, ax = plt.subplots()\nred_patch = mpatches.Patch(color='red', label='The red data')\nax.legend(handles=[red_patch])\n\nplt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There are many supported legend handles. Instead of creating a patch of color\nwe could have created a line with a marker:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.lines as mlines\n\nfig, ax = plt.subplots()\nblue_line = mlines.Line2D([], [], color='blue', marker='*',\n markersize=15, label='Blue stars')\nax.legend(handles=[blue_line])\n\nplt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Legend location\n\nThe location of the legend can be specified by the keyword argument\n*loc*. Please see the documentation at :func:`legend` for more details.\n\nThe ``bbox_to_anchor`` keyword gives a great degree of control for manual\nlegend placement. For example, if you want your Axes legend located at the\nfigure's top right-hand corner instead of the Axes' corner, simply specify\nthe corner's location and the coordinate system of that location::\n\n ax.legend(bbox_to_anchor=(1, 1),\n bbox_transform=fig.transFigure)\n\nMore examples of custom legend placement:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "fig, ax_dict = plt.subplot_mosaic([['top', 'top'], ['bottom', 'BLANK']],\n empty_sentinel=\"BLANK\")\nax_dict['top'].plot([1, 2, 3], label=\"test1\")\nax_dict['top'].plot([3, 2, 1], label=\"test2\")\n# Place a legend above this subplot, expanding itself to\n# fully use the given bounding box.\nax_dict['top'].legend(bbox_to_anchor=(0., 1.02, 1., .102), loc='lower left',\n ncols=2, mode=\"expand\", borderaxespad=0.)\n\nax_dict['bottom'].plot([1, 2, 3], label=\"test1\")\nax_dict['bottom'].plot([3, 2, 1], label=\"test2\")\n# Place a legend to the right of this smaller subplot.\nax_dict['bottom'].legend(bbox_to_anchor=(1.05, 1),\n loc='upper left', borderaxespad=0.)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Figure legends\n\nSometimes it makes more sense to place a legend relative to the (sub)figure\nrather than individual Axes. By using *constrained layout* and\nspecifying \"outside\" at the beginning of the *loc* keyword argument,\nthe legend is drawn outside the Axes on the (sub)figure.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "fig, axs = plt.subplot_mosaic([['left', 'right']], layout='constrained')\n\naxs['left'].plot([1, 2, 3], label=\"test1\")\naxs['left'].plot([3, 2, 1], label=\"test2\")\n\naxs['right'].plot([1, 2, 3], 'C2', label=\"test3\")\naxs['right'].plot([3, 2, 1], 'C3', label=\"test4\")\n# Place a legend to the right of this smaller subplot.\nfig.legend(loc='outside upper right')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This accepts a slightly different grammar than the normal *loc* keyword,\nwhere \"outside right upper\" is different from \"outside upper right\".\n\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "ucl = ['upper', 'center', 'lower']\nlcr = ['left', 'center', 'right']\nfig, ax = plt.subplots(figsize=(6, 4), layout='constrained', facecolor='0.7')\n\nax.plot([1, 2], [1, 2], label='TEST')\n# Place a legend to the right of this smaller subplot.\nfor loc in [\n 'outside upper left',\n 'outside upper center',\n 'outside upper right',\n 'outside lower left',\n 'outside lower center',\n 'outside lower right']:\n fig.legend(loc=loc, title=loc)\n\nfig, ax = plt.subplots(figsize=(6, 4), layout='constrained', facecolor='0.7')\nax.plot([1, 2], [1, 2], label='test')\n\nfor loc in [\n 'outside left upper',\n 'outside right upper',\n 'outside left lower',\n 'outside right lower']:\n fig.legend(loc=loc, title=loc)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Multiple legends on the same Axes\n\nSometimes it is more clear to split legend entries across multiple\nlegends. Whilst the instinctive approach to doing this might be to call\nthe :func:`legend` function multiple times, you will find that only one\nlegend ever exists on the Axes. This has been done so that it is possible\nto call :func:`legend` repeatedly to update the legend to the latest\nhandles on the Axes. To keep old legend instances, we must add them\nmanually to the Axes:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "fig, ax = plt.subplots()\nline1, = ax.plot([1, 2, 3], label=\"Line 1\", linestyle='--')\nline2, = ax.plot([3, 2, 1], label=\"Line 2\", linewidth=4)\n\n# Create a legend for the first line.\nfirst_legend = ax.legend(handles=[line1], loc='upper right')\n\n# Add the legend manually to the Axes.\nax.add_artist(first_legend)\n\n# Create another legend for the second line.\nax.legend(handles=[line2], loc='lower right')\n\nplt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Legend handlers\n\nIn order to create legend entries, handles are given as an argument to an\nappropriate :class:`~matplotlib.legend_handler.HandlerBase` subclass.\nThe choice of handler subclass is determined by the following rules:\n\n1. Update :func:`~matplotlib.legend.Legend.get_legend_handler_map`\n with the value in the ``handler_map`` keyword.\n2. Check if the ``handle`` is in the newly created ``handler_map``.\n3. Check if the type of ``handle`` is in the newly created ``handler_map``.\n4. Check if any of the types in the ``handle``'s mro is in the newly\n created ``handler_map``.\n\nFor completeness, this logic is mostly implemented in\n:func:`~matplotlib.legend.Legend.get_legend_handler`.\n\nAll of this flexibility means that we have the necessary hooks to implement\ncustom handlers for our own type of legend key.\n\nThe simplest example of using custom handlers is to instantiate one of the\nexisting `.legend_handler.HandlerBase` subclasses. For the\nsake of simplicity, let's choose `.legend_handler.HandlerLine2D`\nwhich accepts a *numpoints* argument (numpoints is also a keyword\non the :func:`legend` function for convenience). We can then pass the mapping\nof instance to Handler as a keyword to legend.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from matplotlib.legend_handler import HandlerLine2D\n\nfig, ax = plt.subplots()\nline1, = ax.plot([3, 2, 1], marker='o', label='Line 1')\nline2, = ax.plot([1, 2, 3], marker='o', label='Line 2')\n\nax.legend(handler_map={line1: HandlerLine2D(numpoints=4)}, handlelength=4)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As you can see, \"Line 1\" now has 4 marker points, where \"Line 2\" has 2 (the\ndefault). We have also increased the length of the handles with the\n``handlelength`` keyword to fit the larger legend entry.\nTry the above code, only change the map's key from ``line1`` to\n``type(line1)``. Notice how now both `.Line2D` instances get 4 markers.\n\nAlong with handlers for complex plot types such as errorbars, stem plots\nand histograms, the default ``handler_map`` has a special ``tuple`` handler\n(`.legend_handler.HandlerTuple`) which simply plots the handles on top of one\nanother for each item in the given tuple. The following example demonstrates\ncombining two legend keys on top of one another:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from numpy.random import randn\n\nz = randn(10)\n\nfig, ax = plt.subplots()\nred_dot, = ax.plot(z, \"ro\", markersize=15)\n# Put a white cross over some of the data.\nwhite_cross, = ax.plot(z[:5], \"w+\", markeredgewidth=3, markersize=15)\n\nax.legend([red_dot, (red_dot, white_cross)], [\"Attr A\", \"Attr A+B\"])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `.legend_handler.HandlerTuple` class can also be used to\nassign several legend keys to the same entry:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from matplotlib.legend_handler import HandlerLine2D, HandlerTuple\n\nfig, ax = plt.subplots()\np1, = ax.plot([1, 2.5, 3], 'r-d')\np2, = ax.plot([3, 2, 1], 'k-o')\n\nl = ax.legend([(p1, p2)], ['Two keys'], numpoints=1,\n handler_map={tuple: HandlerTuple(ndivide=None)})" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Implementing a custom legend handler\n\nA custom handler can be implemented to turn any handle into a legend key\n(handles don't necessarily need to be matplotlib artists). The handler must\nimplement a ``legend_artist`` method which returns a single artist for the\nlegend to use. The required signature for ``legend_artist`` is documented at\n`~.legend_handler.HandlerBase.legend_artist`.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.patches as mpatches\n\n\nclass AnyObject:\n pass\n\n\nclass AnyObjectHandler:\n def legend_artist(self, legend, orig_handle, fontsize, handlebox):\n x0, y0 = handlebox.xdescent, handlebox.ydescent\n width, height = handlebox.width, handlebox.height\n patch = mpatches.Rectangle([x0, y0], width, height, facecolor='red',\n edgecolor='black', hatch='xx', lw=3,\n transform=handlebox.get_transform())\n handlebox.add_artist(patch)\n return patch\n\nfig, ax = plt.subplots()\n\nax.legend([AnyObject()], ['My first handler'],\n handler_map={AnyObject: AnyObjectHandler()})" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Alternatively, had we wanted to globally accept ``AnyObject`` instances\nwithout needing to manually set the *handler_map* keyword all the time, we\ncould have registered the new handler with::\n\n from matplotlib.legend import Legend\n Legend.update_default_handler_map({AnyObject: AnyObjectHandler()})\n\nWhilst the power here is clear, remember that there are already many handlers\nimplemented and what you want to achieve may already be easily possible with\nexisting classes. For example, to produce elliptical legend keys, rather than\nrectangular ones:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from matplotlib.legend_handler import HandlerPatch\n\n\nclass HandlerEllipse(HandlerPatch):\n def create_artists(self, legend, orig_handle,\n xdescent, ydescent, width, height, fontsize, trans):\n center = 0.5 * width - 0.5 * xdescent, 0.5 * height - 0.5 * ydescent\n p = mpatches.Ellipse(xy=center, width=width + xdescent,\n height=height + ydescent)\n self.update_prop(p, orig_handle, legend)\n p.set_transform(trans)\n return [p]\n\n\nc = mpatches.Circle((0.5, 0.5), 0.25, facecolor=\"green\",\n edgecolor=\"red\", linewidth=3)\n\nfig, ax = plt.subplots()\n\nax.add_patch(c)\nax.legend([c], [\"An ellipse, not a rectangle\"],\n handler_map={mpatches.Circle: HandlerEllipse()})" ] } ], "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 }