1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
|
.. _plotting-guide-legend:
************
Legend guide
************
.. currentmodule:: matplotlib.pyplot
This legend guide is an extension of the documentation available at
:func:`~matplotlib.pyplot.legend` - please ensure you are familiar with
contents of that documentation before proceeding with this guide.
This guide makes use of some common terms, which are documented here for clarity:
.. glossary::
legend entry
A legend is made up of one or more legend entries. An entry is made up of
exactly one key and one label.
legend key
The colored/patterned marker to the left of each legend label.
legend label
The text which describes the handle represented by the key.
legend handle
The original object which is used to generate an appropriate entry in
the legend.
Controlling the legend entries
==============================
Calling :func:`legend` with no arguments automatically fetches the legend
handles and their associated labels. This functionality is equivalent to::
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles, labels)
The :meth:`~matplotlib.axes.Axes.get_legend_handles_labels` function returns
a list of handles/artists which exist on the Axes which can be used to
generate entries for the resulting legend - it is worth noting however that
not all artists can be added to a legend, at which point a "proxy" will have
to be created (see :ref:`proxy_legend_handles` for further details).
For full control of what is being added to the legend, it is common to pass
the appropriate handles directly to :func:`legend`::
line_up, = plt.plot([1,2,3], label='Line 2')
line_down, = plt.plot([3,2,1], label='Line 1')
plt.legend(handles=[line_up, line_down])
In some cases, it is not possible to set the label of the handle, so it is
possible to pass through the list of labels to :func:`legend`::
line_up, = plt.plot([1,2,3], label='Line 2')
line_down, = plt.plot([3,2,1], label='Line 1')
plt.legend([line_up, line_down], ['Line Up', 'Line Down'])
.. _proxy_legend_handles:
Creating artists specifically for adding to the legend (aka. Proxy artists)
===========================================================================
Not all handles can be turned into legend entries automatically,
so it is often necessary to create an artist which *can*. Legend handles
don't have to exists on the Figure or Axes in order to be used.
Suppose we wanted to create a legend which has an entry for some data which
is represented by a red color:
.. plot::
:include-source:
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
red_patch = mpatches.Patch(color='red', label='The red data')
plt.legend(handles=[red_patch])
plt.show()
There are many supported legend handles, instead of creating a patch of color
we could have created a line with a marker:
.. plot::
:include-source:
import matplotlib.lines as mlines
import matplotlib.pyplot as plt
blue_line = mlines.Line2D([], [], color='blue', marker='*',
markersize=15, label='Blue stars')
plt.legend(handles=[blue_line])
plt.show()
Legend location
===============
The location of the legend can be specified by the keyword argument
*loc*. Please see the documentation at :func:`legend` for more details.
The ``bbox_to_anchor`` keyword gives a great degree of control for manual
legend placement. For example, if you want your axes legend located at the
figure's top right-hand corner instead of the axes' corner, simply specify
the corner's location, and the coordinate system of that location::
plt.legend(bbox_to_anchor=(1, 1),
bbox_transform=plt.gcf().transFigure)
More examples of custom legend placement:
.. plot:: users/plotting/examples/simple_legend01.py
:include-source:
Multiple legends on the same Axes
=================================
Sometimes it is more clear to split legend entries across multiple
legends. Whilst the instinctive approach to doing this might be to call
the :func:`legend` function multiple times, you will find that only one
legend ever exists on the Axes. This has been done so that it is possible
to call :func:`legend` repeatedly to update the legend to the latest
handles on the Axes, so to persist old legend instances, we must add them
manually to the Axes:
.. plot:: users/plotting/examples/simple_legend02.py
:include-source:
Legend Handlers
===============
In order to create legend entries, handles are given as an argument to an
appropriate :class:`~matplotlib.legend_handler.HandlerBase` subclass.
The choice of handler subclass is determined by the following rules:
1. Update :func:`~matplotlib.legend.Legend.get_legend_handler_map`
with the value in the ``handler_map`` keyword.
2. Check if the ``handle`` is in the newly created ``handler_map``.
3. Check if the type of ``handle`` is in the newly created
``handler_map``.
4. Check if any of the types in the ``handle``'s mro is in the newly
created ``handler_map``.
For completeness, this logic is mostly implemented in
:func:`~matplotlib.legend.Legend.get_legend_handler`.
All of this flexibility means that we have the necessary hooks to implement
custom handlers for our own type of legend key.
The simplest example of using custom handlers is to instantiate one of the
existing :class:`~matplotlib.legend_handler.HandlerBase` subclasses. For the
sake of simplicity, let's choose :class:`matplotlib.legend_handler.HandlerLine2D`
which accepts a ``numpoints`` argument (note numpoints is a keyword
on the :func:`legend` function for convenience). We can then pass the mapping
of instance to Handler as a keyword to legend.
.. plot::
:include-source:
import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerLine2D
line1, = plt.plot([3,2,1], marker='o', label='Line 1')
line2, = plt.plot([1,2,3], marker='o', label='Line 2')
plt.legend(handler_map={line1: HandlerLine2D(numpoints=4)})
As you can see, "Line 1" now has 4 marker points, where "Line 2" has 2 (the
default). Try the above code, only change the map's key from ``line1`` to
``type(line1)``. Notice how now both :class:`~matplotlib.lines.Line2D` instances
get 4 markers.
Along with handlers for complex plot types such as errorbars, stem plots
and histograms, the default ``handler_map`` has a special ``tuple`` handler
(:class:`~matplotlib.legend_handler.HandlerTuple`) which simply plots
the handles on top of one another for each item in the given tuple. The
following example demonstrates combining two legend keys on top of one another:
.. plot::
:include-source:
import matplotlib.pyplot as plt
from numpy.random import randn
z = randn(10)
red_dot, = plt.plot(z, "ro", markersize=15)
# Put a white cross over some of the data.
white_cross, = plt.plot(z[:5], "w+", markeredgewidth=3, markersize=15)
plt.legend([red_dot, (red_dot, white_cross)], ["Attr A", "Attr A+B"])
Implementing a custom legend handler
------------------------------------
A custom handler can be implemented to turn any handle into a legend key (handles
don't necessarily need to be matplotlib artists).
The handler must implement a "legend_artist" method which returns a
single artist for the legend to use. Signature details about the "legend_artist"
are documented at :meth:`~matplotlib.legend_handler.HandlerBase.legend_artist`.
.. plot::
:include-source:
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
class AnyObject(object):
pass
class AnyObjectHandler(object):
def legend_artist(self, legend, orig_handle, fontsize, handlebox):
x0, y0 = handlebox.xdescent, handlebox.ydescent
width, height = handlebox.width, handlebox.height
patch = mpatches.Rectangle([x0, y0], width, height, facecolor='red',
edgecolor='black', hatch='xx', lw=3,
transform=handlebox.get_transform())
handlebox.add_artist(patch)
return patch
plt.legend([AnyObject()], ['My first handler'],
handler_map={AnyObject: AnyObjectHandler()})
Alternatively, had we wanted to globally accept ``AnyObject`` instances without
needing to manually set the ``handler_map`` keyword all the time, we could have
registered the new handler with::
from matplotlib.legend import Legend
Legend.update_default_handler_map({AnyObject: AnyObjectHandler()})
Whilst the power here is clear, remember that there are already many handlers
implemented and what you want to achieve may already be easily possible with
existing classes. For example, to produce elliptical legend keys, rather than
rectangular ones:
.. plot::
:include-source:
from matplotlib.legend_handler import HandlerPatch
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
class HandlerEllipse(HandlerPatch):
def create_artists(self, legend, orig_handle,
xdescent, ydescent, width, height, fontsize, trans):
center = 0.5 * width - 0.5 * xdescent, 0.5 * height - 0.5 * ydescent
p = mpatches.Ellipse(xy=center, width=width + xdescent,
height=height + ydescent)
self.update_prop(p, orig_handle, legend)
p.set_transform(trans)
return [p]
c = mpatches.Circle((0.5, 0.5), 0.25, facecolor="green",
edgecolor="red", linewidth=3)
plt.gca().add_patch(c)
plt.legend([c], ["An ellipse, not a rectangle"],
handler_map={mpatches.Circle: HandlerEllipse()})
Known examples of using legend
==============================
Here is a non-exhaustive list of the examples available involving legend
being used in various ways:
* :ref:`lines_bars_and_markers-scatter_with_legend`
* :ref:`api-legend_demo`
* :ref:`pylab_examples-contourf_hatching`
* :ref:`pylab_examples-figlegend_demo`
* :ref:`pylab_examples-scatter_symbol`
|