""" The legend module defines the Legend class, which is responsible for drawing legends associated with axes and/or figures.
.. important::
It is unlikely that you would ever create a Legend instance manually. Most users would normally create a legend via the :meth:`~matplotlib.axes.Axes.legend` function. For more details on legends there is also a :doc:`legend guide </tutorials/intermediate/legend_guide>`.
The Legend class can be considered as a container of legend handles and legend texts. Creation of corresponding legend handles from the plot elements in the axes or figures (e.g., lines, patches, etc.) are specified by the handler map, which defines the mapping between the plot elements and the legend handlers to be used (the default legend handlers are defined in the :mod:`~matplotlib.legend_handler` module). Note that not all kinds of artist are supported by the legend yet by default but it is possible to extend the legend handler's capabilities to support arbitrary objects. See the :doc:`legend guide </tutorials/intermediate/legend_guide>` for more information. """
CircleCollection, PathCollection, PolyCollection)
""" Wrapper around a `.Legend` to support mouse dragging.
Parameters ---------- legend : `.Legend` The `.Legend` instance to wrap. use_blit : bool, optional Use blitting for faster image composition. For details see :ref:`func-animation`. update : {'loc', 'bbox'}, optional If "loc", update the *loc* parameter of the legend upon finalizing. If "bbox", update the *bbox_to_anchor* parameter. """ self.legend = legend
if update in ["loc", "bbox"]: self._update = update else: raise ValueError("update parameter '%s' is not supported." % update)
DraggableOffsetBox.__init__(self, legend, legend._legend_box, use_blit=use_blit)
return self.legend.contains(evt)
loc_in_canvas = self.get_loc_in_canvas()
if self._update == "loc": self._update_loc(loc_in_canvas) elif self._update == "bbox": self._update_bbox_to_anchor(loc_in_canvas) else: raise RuntimeError("update parameter '%s' is not supported." % self.update)
bbox = self.legend.get_bbox_to_anchor()
# if bbox has zero width or height, the transformation is # ill-defined. Fall back to the defaul bbox_to_anchor. if bbox.width == 0 or bbox.height == 0: self.legend.set_bbox_to_anchor(None) bbox = self.legend.get_bbox_to_anchor()
_bbox_transform = BboxTransformFrom(bbox) self.legend._loc = tuple( _bbox_transform.transform_point(loc_in_canvas) )
tr = self.legend.axes.transAxes loc_in_bbox = tr.transform_point(loc_in_canvas)
self.legend.set_bbox_to_anchor(loc_in_bbox)
loc : int or string or pair of floats, default: :rc:`legend.loc` ('best' for \ axes, 'upper right' for figures) The location of the legend. Possible codes are:
=============== ============= Location String Location Code =============== ============= 'best' 0 'upper right' 1 'upper left' 2 'lower left' 3 'lower right' 4 'right' 5 'center left' 6 'center right' 7 'lower center' 8 'upper center' 9 'center' 10 =============== =============
Alternatively can be a 2-tuple giving ``x, y`` of the lower-left corner of the legend in axes coordinates (in which case ``bbox_to_anchor`` will be ignored).
The 'best' option can be quite slow for plots with large amounts of data. Your plotting speed may benefit from providing a specific location.
bbox_to_anchor : `.BboxBase`, 2-tuple, or 4-tuple of floats Box that is used to position the legend in conjunction with *loc*. Defaults to `axes.bbox` (if called as a method to `.Axes.legend`) or `figure.bbox` (if `.Figure.legend`). This argument allows arbitrary placement of the legend.
Bbox coordinates are interpreted in the coordinate system given by `bbox_transform`, with the default transform Axes or Figure coordinates, depending on which ``legend`` is called.
If a 4-tuple or `.BboxBase` is given, then it specifies the bbox ``(x, y, width, height)`` that the legend is placed in. To put the legend in the best location in the bottom right quadrant of the axes (or figure)::
loc='best', bbox_to_anchor=(0.5, 0., 0.5, 0.5)
A 2-tuple ``(x, y)`` places the corner of the legend specified by *loc* at x, y. For example, to put the legend's upper right-hand corner in the center of the axes (or figure) the following keywords can be used::
loc='upper right', bbox_to_anchor=(0.5, 0.5)
ncol : integer The number of columns that the legend has. Default is 1.
prop : None or :class:`matplotlib.font_manager.FontProperties` or dict The font properties of the legend. If None (default), the current :data:`matplotlib.rcParams` will be used.
fontsize : int or float or {'xx-small', 'x-small', 'small', 'medium', \ 'large', 'x-large', 'xx-large'} Controls the font size of the legend. If the value is numeric the size will be the absolute font size in points. String values are relative to the current default font size. This argument is only used if `prop` is not specified.
numpoints : None or int The number of marker points in the legend when creating a legend entry for a `.Line2D` (line). Default is ``None``, which will take the value from :rc:`legend.numpoints`.
scatterpoints : None or int The number of marker points in the legend when creating a legend entry for a `.PathCollection` (scatter plot). Default is ``None``, which will take the value from :rc:`legend.scatterpoints`.
scatteryoffsets : iterable of floats The vertical offset (relative to the font size) for the markers created for a scatter plot legend entry. 0.0 is at the base the legend text, and 1.0 is at the top. To draw all markers at the same height, set to ``[0.5]``. Default is ``[0.375, 0.5, 0.3125]``.
markerscale : None or int or float The relative size of legend markers compared with the originally drawn ones. Default is ``None``, which will take the value from :rc:`legend.markerscale`.
markerfirst : bool If *True*, legend marker is placed to the left of the legend label. If *False*, legend marker is placed to the right of the legend label. Default is *True*.
frameon : None or bool Control whether the legend should be drawn on a patch (frame). Default is ``None``, which will take the value from :rc:`legend.frameon`.
fancybox : None or bool Control whether round edges should be enabled around the :class:`~matplotlib.patches.FancyBboxPatch` which makes up the legend's background. Default is ``None``, which will take the value from :rc:`legend.fancybox`.
shadow : None or bool Control whether to draw a shadow behind the legend. Default is ``None``, which will take the value from :rc:`legend.shadow`.
framealpha : None or float Control the alpha transparency of the legend's background. Default is ``None``, which will take the value from :rc:`legend.framealpha`. If shadow is activated and *framealpha* is ``None``, the default value is ignored.
facecolor : None or "inherit" or a color spec Control the legend's background color. Default is ``None``, which will take the value from :rc:`legend.facecolor`. If ``"inherit"``, it will take :rc:`axes.facecolor`.
edgecolor : None or "inherit" or a color spec Control the legend's background patch edge color. Default is ``None``, which will take the value from :rc:`legend.edgecolor` If ``"inherit"``, it will take :rc:`axes.edgecolor`.
mode : {"expand", None} If `mode` is set to ``"expand"`` the legend will be horizontally expanded to fill the axes area (or `bbox_to_anchor` if defines the legend's size).
bbox_transform : None or :class:`matplotlib.transforms.Transform` The transform for the bounding box (`bbox_to_anchor`). For a value of ``None`` (default) the Axes' :data:`~matplotlib.axes.Axes.transAxes` transform will be used.
title : str or None The legend's title. Default is no title (``None``).
title_fontsize: str or None The fontsize of the legend's title. Default is the default fontsize.
borderpad : float or None The fractional whitespace inside the legend border. Measured in font-size units. Default is ``None``, which will take the value from :rc:`legend.borderpad`.
labelspacing : float or None The vertical space between the legend entries. Measured in font-size units. Default is ``None``, which will take the value from :rc:`legend.labelspacing`.
handlelength : float or None The length of the legend handles. Measured in font-size units. Default is ``None``, which will take the value from :rc:`legend.handlelength`.
handletextpad : float or None The pad between the legend handle and text. Measured in font-size units. Default is ``None``, which will take the value from :rc:`legend.handletextpad`.
borderaxespad : float or None The pad between the axes and legend border. Measured in font-size units. Default is ``None``, which will take the value from :rc:`legend.borderaxespad`.
columnspacing : float or None The spacing between columns. Measured in font-size units. Default is ``None``, which will take the value from :rc:`legend.columnspacing`.
handler_map : dict or None The custom dictionary mapping instances or types to a legend handler. This `handler_map` updates the default handler map found at :func:`matplotlib.legend.Legend.get_legend_handler_map`.
'''
""" Place a legend on the axes at location loc.
""" 'upper right': 1, 'upper left': 2, 'lower left': 3, 'lower right': 4, 'right': 5, 'center left': 6, 'center right': 7, 'lower center': 8, 'upper center': 9, 'center': 10, }
def __str__(self): return "Legend"
loc=None, numpoints=None, # the number of points in the legend line markerscale=None, # the relative size of legend markers # vs. original markerfirst=True, # controls ordering (left-to-right) of # legend marker and label scatterpoints=None, # number of scatter points scatteryoffsets=None, prop=None, # properties for the legend texts fontsize=None, # keyword to set font size directly
# spacing & pad defined as a fraction of the font-size borderpad=None, # the whitespace inside the legend border labelspacing=None, # the vertical space between the legend # entries handlelength=None, # the length of the legend handles handleheight=None, # the height of the legend handles handletextpad=None, # the pad between the legend handle # and text borderaxespad=None, # the pad between the axes and legend # border columnspacing=None, # spacing between columns
ncol=1, # number of columns mode=None, # mode for horizontal distribution of columns. # None, "expand"
fancybox=None, # True use a fancy box, false use a rounded # box, none use rc shadow=None, title=None, # set a title for the legend title_fontsize=None, # set to ax.fontsize if None framealpha=None, # set frame alpha edgecolor=None, # frame patch edgecolor facecolor=None, # frame patch facecolor
bbox_to_anchor=None, # bbox that the legend will be anchored. bbox_transform=None, # transform for the bbox frameon=None, # draw frame handler_map=None, ): """ Parameters ---------- parent : `~matplotlib.axes.Axes` or `.Figure` The artist that contains the legend.
handles : sequence of `.Artist` A list of Artists (lines, patches) to be added to the legend.
labels : sequence of strings A list of labels to show next to the artists. The length of handles and labels should be the same. If they are not, they are truncated to the smaller of both lengths.
Other Parameters ----------------
%(_legend_kw_doc)s
Notes -----
Users can specify any arbitrary location for the legend using the *bbox_to_anchor* keyword argument. bbox_to_anchor can be an instance of BboxBase(or its derivatives) or a tuple of 2 or 4 floats. See :meth:`set_bbox_to_anchor` for more detail.
The legend location can be specified by setting *loc* with a tuple of 2 floats, which is interpreted as the lower-left corner of the legend in the normalized axes coordinate. """ # local import only to avoid circularity
else: self.prop.set_size(rcParams["legend.fontsize"]) else: self.prop = prop
#: A dictionary with the extra handler mappings for this Legend #: instance.
"scatterpoints", "handleheight", 'borderpad', 'labelspacing', 'handlelength', 'handletextpad', 'borderaxespad']: else: # trim handles and labels if illegal label... warnings.warn('The handle {!r} has a label of {!r} which ' 'cannot be automatically added to the ' 'legend.'.format(handle, label)) else:
ncol = 1
raise ValueError("numpoints must be > 0; it was %d" % numpoints)
# introduce y-offset for handles of the scatter plot else: self._scatteryoffsets = np.asarray(scatteryoffsets) reps)[:self.scatterpoints]
# _legend_box is an OffsetBox instance that contains all # legend items and will be initialized from _init_legend_box() # method.
else: raise TypeError("Legend needs either Axes or Figure as parent")
loc = 'upper right' if self.isaxes: warnings.warn('Unrecognized location "%s". Falling back ' 'on "best"; valid locations are\n\t%s\n' % (loc, '\n\t'.join(self.codes))) loc = 0 else: warnings.warn('Unrecognized location "%s". Falling back ' 'on "upper right"; ' 'valid locations are\n\t%s\n' % (loc, '\n\t'.join(self.codes))) loc = 1 else: warnings.warn('Automatic legend placement (loc="best") not ' 'implemented for figure legend. ' 'Falling back on "upper right".') loc = 1
# We use FancyBboxPatch to draw a legend frame. The location # and size of the box will be updated during the drawing time.
edgecolor = rcParams["axes.edgecolor"]
xy=(0.0, 0.0), width=1., height=1., facecolor=facecolor, edgecolor=edgecolor, mutation_scale=self._fontsize, snap=True )
# The width and height of the legendPatch will be set (in the # draw()) to the length that includes the padding. Thus we set # pad=0 here.
rounding_size=0.2) else: self.legendPatch.set_boxstyle("square", pad=0)
# init with null renderer
# If shadow is activated use framealpha if not # explicitly passed. See Issue 8943 self.get_frame().set_alpha(1) else: else: self.get_frame().set_alpha(framealpha)
# figure out title fontsize:
""" Set the boilerplate props for artists added to axes. """ # a.set_axes(self.axes)
# find_offset function will be provided to _legend_box and # _legend_box will draw itself at the location of the return # value of the find_offset.
"Helper function to locate the legend."
self.get_bbox_to_anchor(), renderer) else: # Axes or figure coordinates. fx, fy = self._loc bbox = self.get_bbox_to_anchor() x, y = bbox.x0 + bbox.width * fx, bbox.y0 + bbox.height * fy
def draw(self, renderer): "Draw everything that belongs to the legend." return
# if mode == fill, set the width of the legend_box to the # width of the paret (minus pads) pad = 2 * (self.borderaxespad + self.borderpad) * fontsize self._legend_box.set_width(self.get_bbox_to_anchor().width - pad)
# update the location and size of the legend. This needs to # be done in any case to clip the figure right. bbox.width, bbox.height)
shadow = Shadow(self.legendPatch, 2, -2) shadow.draw(renderer)
""" Return the approximate height of the text. This is used to place the legend handle. """ else: return renderer.points_to_pixels(self._fontsize)
# _default_handler_map defines the default mapping between plot # elements and the legend handlers.
StemContainer: legend_handler.HandlerStem(), ErrorbarContainer: legend_handler.HandlerErrorbar(), Line2D: legend_handler.HandlerLine2D(), Patch: legend_handler.HandlerPatch(), LineCollection: legend_handler.HandlerLineCollection(), RegularPolyCollection: legend_handler.HandlerRegularPolyCollection(), CircleCollection: legend_handler.HandlerCircleCollection(), BarContainer: legend_handler.HandlerPatch( update_func=legend_handler.update_from_first_child), tuple: legend_handler.HandlerTuple(), PathCollection: legend_handler.HandlerPathCollection(), PolyCollection: legend_handler.HandlerPolyCollection() }
# (get|set|update)_default_handler_maps are public interfaces to # modify the default handler map.
def get_default_handler_map(cls): """ A class method that returns the default handler map. """
def set_default_handler_map(cls, handler_map): """ A class method to set the default handler map. """ cls._default_handler_map = handler_map
def update_default_handler_map(cls, handler_map): """ A class method to update the default handler map. """ cls._default_handler_map.update(handler_map)
""" Return the handler map. """
hm = default_handler_map.copy() hm.update(self._custom_handler_map) return hm else:
def get_legend_handler(legend_handler_map, orig_handle): """ Return a legend handler from *legend_handler_map* that corresponds to *orig_handler*.
*legend_handler_map* should be a dictionary object (that is returned by the get_legend_handler_map method).
It first checks if the *orig_handle* itself is a key in the *legend_hanler_map* and return the associated value. Otherwise, it checks for each of the classes in its method-resolution-order. If no matching key is found, it returns ``None``. """
return None
""" Initialize the legend_box. The legend_box is an instance of the OffsetBox, which is packed with legend handles and texts. Once packed, their location is calculated during the drawing time. """
# legend_box is a HPacker, horizontally packed with # columns. Each column is a VPacker, vertically packed with # legend items. Each legend item is HPacker packed with # legend handleBox and labelBox. handleBox is an instance of # offsetbox.DrawingArea which contains legend handle. labelBox # is an instance of offsetbox.TextArea which contains legend # text.
horizontalalignment='left', fontproperties=self.prop, )
# The approximate height and descent of text. These values are # only used for plotting the legend handle. # 0.35 and 0.7 are just heuristic numbers and may need to be improved. # each handle needs to be drawn inside a box of (x, y, w, h) = # (0, -descent, width, height). And their coordinates should # be given in the display coordinates.
# The transformation of each handle will be automatically set # to self.get_trasnform(). If the artist does not use its # default transform (e.g., Collections), you need to # manually set their transform to the self.get_transform().
warnings.warn( "Legend does not support {!r} instances.\nA proxy artist " "may be used instead.\nSee: " "http://matplotlib.org/users/legend_guide.html" "#creating-artists-specifically-for-adding-to-the-legend-" "aka-proxy-artists".format(orig_handle) ) # We don't have a handle for this artist, so we just defer # to None. handle_list.append(None) else: multilinebaseline=True, minimumdescent=True) height=height, xdescent=0., ydescent=descent)
# Create the artist for the legend which represents the # original artist/handle. fontsize, handlebox))
# We calculate number of rows in each column. The first # (num_largecol) columns will have (nrows+1) rows, and remaining # (num_smallcol) columns will have (nrows) rows. # starting index of each column and number of rows in it. else: cols = []
# pack handleBox and labelBox into itemBox sep=self.handletextpad * fontsize, children=[h, t] if markerfirst else [t, h], align="baseline") for h, t in handles_and_labels[i0:i0 + di]] # minimumdescent=False for the text of the last row of the column else: itemBoxes[-1].get_children()[0].set_minimumdescent(False)
# pack columnBox sep=self.labelspacing * fontsize, align=alignment, children=itemBoxes))
sep=sep, align="baseline", mode=mode, children=columnbox) sep=self.labelspacing * fontsize, align="center", children=[self._legend_title_box, self._legend_handle_box])
""" Returns list of vertices and extents covered by the plot.
Returns a two long list.
First element is a list of (x, y) vertices (in display-coordinates) covered by all the lines and line collections, in the legend's handles.
Second element is a list of bounding boxes for all the patches in the legend's handles. """ # should always hold because function is only called internally
transform = handle.get_data_transform() bboxes.append(handle.get_bbox().transformed(transform)) else:
transform, transOffset, hoffsets, paths = handle._prepare_points()
if len(hoffsets): for offset in transOffset.transform(hoffsets): offsets.append(offset)
except ValueError: vertices = np.array([])
''' Set draw frame to b.
Parameters ---------- b : bool ''' self.set_frame_on(b)
'Return a list of child artists.' children = [] if self._legend_box: children.append(self._legend_box) children.append(self.get_frame())
return children
''' Return the `~.patches.Rectangle` instances used to frame the legend. '''
'Return a list of `~.lines.Line2D` instances in the legend.' return [h for h in self.legendHandles if isinstance(h, Line2D)]
'Return a list of `~.patches.Patch` instances in the legend.' return silent_list('Patch', [h for h in self.legendHandles if isinstance(h, Patch)])
'Return a list of `~.text.Text` instances in the legend.' return silent_list('Text', self.texts)
""" Set the legend title. Fontproperties can be optionally set with *prop* parameter. """ else:
'Return the `.Text` instance for the legend title.' return self._legend_title_box._text
'Return extent of the legend.' if renderer is None: renderer = self.figure._cachedRenderer return self._legend_box.get_window_extent(renderer=renderer)
""" Like `.Legend.get_window_extent`, but uses the box for the legend.
Parameters ---------- renderer : `.RendererBase` instance renderer that will be used to draw the figures (i.e. ``fig.canvas.get_renderer()``)
Returns ------- `.BboxBase` : containing the bounding box in figure pixel co-ordinates. """ return self._legend_box.get_window_extent(renderer)
"""Get whether the legend box patch is drawn.""" return self._drawFrame
""" Set whether the legend box patch is drawn.
Parameters ---------- b : bool """ self._drawFrame = b self.stale = True
"""Return the bbox that the legend will be anchored to.""" else:
""" Set the bbox that the legend will be anchored to.
*bbox* can be
- A `.BboxBase` instance - A tuple of ``(left, bottom, width, height)`` in the given transform (normalized axes coordinate if None) - A tuple of ``(left, bottom)`` where the width and height will be assumed to be zero. """ self._bbox_to_anchor = bbox else: except TypeError: raise ValueError("Invalid argument for bbox : %s" % str(bbox))
bbox = [bbox[0], bbox[1], 0, 0]
transform)
""" Place the *bbox* inside the *parentbbox* according to a given location code. Return the (x,y) coordinate of the bbox.
- loc: a location code in range(1, 11). This corresponds to the possible values for self._loc, excluding "best".
- bbox: bbox to be placed, display coordinate units. - parentbbox: a parent box which will contain the bbox. In display coordinates. """
UL: "NW", LL: "SW", LR: "SE", R: "E", CL: "W", CR: "E", LC: "S", UC: "N", C: "C"}
""" Determine the best location to place the legend.
*consider* is a list of ``(x, y)`` pairs to consider as a potential lower-left corner of the legend. All are display coords. """ # should always hold because function is only called internally
self.get_bbox_to_anchor(), renderer) for x in range(1, len(self.codes))]
# XXX TODO: If markers are present, it would be good to # take them into account when checking vertex overlaps in # the next line. + legendBox.count_contains(offsets) + legendBox.count_overlaps(bboxes) + sum(line.intersects_bbox(legendBox, filled=False) for line in lines)) return l, b # Include the index to favor lower codes in case of a tie.
return self.legendPatch.contains(event)
""" Enable or disable mouse dragging support of the legend.
Parameters ---------- state : bool Whether mouse dragging is enabled. use_blit : bool, optional Use blitting for faster image composition. For details see :ref:`func-animation`. update : {'loc', 'bbox'}, optional The legend parameter to be changed when dragged:
- 'loc': update the *loc* parameter of the legend - 'bbox': update the *bbox_to_anchor* parameter of the legend
Returns ------- If *state* is ``True`` this returns the `~.DraggableLegend` helper instance. Otherwise this returns ``None``. """ if state: if self._draggable is None: self._draggable = DraggableLegend(self, use_blit, update=update) else: if self._draggable is not None: self._draggable.disconnect() self._draggable = None return self._draggable
"""Return ``True`` if the legend is draggable, ``False`` otherwise.""" return self._draggable is not None
""" Set the draggable state -- if state is
* None : toggle the current state
* True : turn draggable on
* False : turn draggable off
If draggable is on, you can drag the legend on the canvas with the mouse. The `.DraggableLegend` helper instance is returned if draggable is on.
The update parameter control which parameter of the legend changes when dragged. If update is "loc", the *loc* parameter of the legend is changed. If "bbox", the *bbox_to_anchor* parameter is changed. """ warn_deprecated("2.2", message="Legend.draggable() is drepecated in " "favor of Legend.set_draggable(). " "Legend.draggable may be reintroduced as a " "property in future releases.")
if state is None: state = not self.get_draggable() # toggle state
self.set_draggable(state, use_blit, update)
return self._draggable
# Helper functions to parse legend arguments for both `figure.legend` and # `axes.legend`: """ Return a generator of artists that can be used as handles in a legend.
""" ax.collections + ax.containers) # support parasite axes: for axx in ax.parasites: handles_original += (axx.lines + axx.patches + axx.collections + axx.containers)
""" Return handles and labels for legend, internal method.
"""
""" Get the handles and labels from the calls to either ``figure.legend`` or ``axes.legend``.
``axs`` is a list of axes (to get legend artists from) """
warnings.warn("You have mixed positional and keyword arguments, some " "input may be discarded.")
# if got both handles and labels as kwargs, make same length handles, labels = zip(*zip(handles, labels))
labels = [handle.get_label() for handle in handles]
# Get as many handles as there are labels. handles = [handle for handle, label in zip(_get_legend_handles(axs, handlers), labels)]
# No arguments - automatically detect labels and handles. log.warning('No handles with labels found to put in legend.')
# One argument. User defined labels - automatic handle detection. labels, = args # Get as many handles as there are labels. handles = [handle for handle, label in zip(_get_legend_handles(axs, handlers), labels)]
# Two arguments: # * user defined handles and labels
else: raise TypeError('Invalid arguments to legend.')
|