legend.py 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265
  1. """
  2. The legend module defines the Legend class, which is responsible for
  3. drawing legends associated with axes and/or figures.
  4. .. important::
  5. It is unlikely that you would ever create a Legend instance
  6. manually. Most users would normally create a legend via the
  7. :meth:`~matplotlib.axes.Axes.legend` function. For more details on legends
  8. there is also a :doc:`legend guide </tutorials/intermediate/legend_guide>`.
  9. The Legend class can be considered as a container of legend handles and
  10. legend texts. Creation of corresponding legend handles from the plot elements
  11. in the axes or figures (e.g., lines, patches, etc.) are specified by the
  12. handler map, which defines the mapping between the plot elements and the
  13. legend handlers to be used (the default legend handlers are defined in the
  14. :mod:`~matplotlib.legend_handler` module). Note that not all kinds of
  15. artist are supported by the legend yet by default but it is possible to
  16. extend the legend handler's capabilities to support arbitrary objects. See
  17. the :doc:`legend guide </tutorials/intermediate/legend_guide>` for more
  18. information.
  19. """
  20. import logging
  21. import time
  22. import numpy as np
  23. from matplotlib import rcParams
  24. from matplotlib import cbook, docstring
  25. from matplotlib.artist import Artist, allow_rasterization
  26. from matplotlib.cbook import silent_list
  27. from matplotlib.font_manager import FontProperties
  28. from matplotlib.lines import Line2D
  29. from matplotlib.patches import Patch, Rectangle, Shadow, FancyBboxPatch
  30. from matplotlib.collections import (LineCollection, RegularPolyCollection,
  31. CircleCollection, PathCollection,
  32. PolyCollection)
  33. from matplotlib.transforms import Bbox, BboxBase, TransformedBbox
  34. from matplotlib.transforms import BboxTransformTo, BboxTransformFrom
  35. from matplotlib.offsetbox import HPacker, VPacker, TextArea, DrawingArea
  36. from matplotlib.offsetbox import DraggableOffsetBox
  37. from matplotlib.container import ErrorbarContainer, BarContainer, StemContainer
  38. from . import legend_handler
  39. class DraggableLegend(DraggableOffsetBox):
  40. def __init__(self, legend, use_blit=False, update="loc"):
  41. """
  42. Wrapper around a `.Legend` to support mouse dragging.
  43. Parameters
  44. ----------
  45. legend : `.Legend`
  46. The `.Legend` instance to wrap.
  47. use_blit : bool, optional
  48. Use blitting for faster image composition. For details see
  49. :ref:`func-animation`.
  50. update : {'loc', 'bbox'}, optional
  51. If "loc", update the *loc* parameter of the legend upon finalizing.
  52. If "bbox", update the *bbox_to_anchor* parameter.
  53. """
  54. self.legend = legend
  55. cbook._check_in_list(["loc", "bbox"], update=update)
  56. self._update = update
  57. DraggableOffsetBox.__init__(self, legend, legend._legend_box,
  58. use_blit=use_blit)
  59. def artist_picker(self, legend, evt):
  60. return self.legend.contains(evt)
  61. def finalize_offset(self):
  62. if self._update == "loc":
  63. self._update_loc(self.get_loc_in_canvas())
  64. elif self._update == "bbox":
  65. self._bbox_to_anchor(self.get_loc_in_canvas())
  66. def _update_loc(self, loc_in_canvas):
  67. bbox = self.legend.get_bbox_to_anchor()
  68. # if bbox has zero width or height, the transformation is
  69. # ill-defined. Fall back to the default bbox_to_anchor.
  70. if bbox.width == 0 or bbox.height == 0:
  71. self.legend.set_bbox_to_anchor(None)
  72. bbox = self.legend.get_bbox_to_anchor()
  73. _bbox_transform = BboxTransformFrom(bbox)
  74. self.legend._loc = tuple(_bbox_transform.transform(loc_in_canvas))
  75. def _update_bbox_to_anchor(self, loc_in_canvas):
  76. loc_in_bbox = self.legend.axes.transAxes.transform(loc_in_canvas)
  77. self.legend.set_bbox_to_anchor(loc_in_bbox)
  78. _legend_kw_doc = '''
  79. loc : str or pair of floats, default: :rc:`legend.loc` ('best' for axes, \
  80. 'upper right' for figures)
  81. The location of the legend.
  82. The strings
  83. ``'upper left', 'upper right', 'lower left', 'lower right'``
  84. place the legend at the corresponding corner of the axes/figure.
  85. The strings
  86. ``'upper center', 'lower center', 'center left', 'center right'``
  87. place the legend at the center of the corresponding edge of the
  88. axes/figure.
  89. The string ``'center'`` places the legend at the center of the axes/figure.
  90. The string ``'best'`` places the legend at the location, among the nine
  91. locations defined so far, with the minimum overlap with other drawn
  92. artists. This option can be quite slow for plots with large amounts of
  93. data; your plotting speed may benefit from providing a specific location.
  94. The location can also be a 2-tuple giving the coordinates of the lower-left
  95. corner of the legend in axes coordinates (in which case *bbox_to_anchor*
  96. will be ignored).
  97. For back-compatibility, ``'center right'`` (but no other location) can also
  98. be spelled ``'right'``, and each "string" locations can also be given as a
  99. numeric value:
  100. =============== =============
  101. Location String Location Code
  102. =============== =============
  103. 'best' 0
  104. 'upper right' 1
  105. 'upper left' 2
  106. 'lower left' 3
  107. 'lower right' 4
  108. 'right' 5
  109. 'center left' 6
  110. 'center right' 7
  111. 'lower center' 8
  112. 'upper center' 9
  113. 'center' 10
  114. =============== =============
  115. bbox_to_anchor : `.BboxBase`, 2-tuple, or 4-tuple of floats
  116. Box that is used to position the legend in conjunction with *loc*.
  117. Defaults to `axes.bbox` (if called as a method to `.Axes.legend`) or
  118. `figure.bbox` (if `.Figure.legend`). This argument allows arbitrary
  119. placement of the legend.
  120. Bbox coordinates are interpreted in the coordinate system given by
  121. `bbox_transform`, with the default transform
  122. Axes or Figure coordinates, depending on which ``legend`` is called.
  123. If a 4-tuple or `.BboxBase` is given, then it specifies the bbox
  124. ``(x, y, width, height)`` that the legend is placed in.
  125. To put the legend in the best location in the bottom right
  126. quadrant of the axes (or figure)::
  127. loc='best', bbox_to_anchor=(0.5, 0., 0.5, 0.5)
  128. A 2-tuple ``(x, y)`` places the corner of the legend specified by *loc* at
  129. x, y. For example, to put the legend's upper right-hand corner in the
  130. center of the axes (or figure) the following keywords can be used::
  131. loc='upper right', bbox_to_anchor=(0.5, 0.5)
  132. ncol : integer
  133. The number of columns that the legend has. Default is 1.
  134. prop : None or :class:`matplotlib.font_manager.FontProperties` or dict
  135. The font properties of the legend. If None (default), the current
  136. :data:`matplotlib.rcParams` will be used.
  137. fontsize : int or float or {'xx-small', 'x-small', 'small', 'medium', \
  138. 'large', 'x-large', 'xx-large'}
  139. The font size of the legend. If the value is numeric the size will be the
  140. absolute font size in points. String values are relative to the current
  141. default font size. This argument is only used if *prop* is not specified.
  142. numpoints : None or int
  143. The number of marker points in the legend when creating a legend
  144. entry for a `.Line2D` (line).
  145. Default is ``None``, which means using :rc:`legend.numpoints`.
  146. scatterpoints : None or int
  147. The number of marker points in the legend when creating
  148. a legend entry for a `.PathCollection` (scatter plot).
  149. Default is ``None``, which means using :rc:`legend.scatterpoints`.
  150. scatteryoffsets : iterable of floats
  151. The vertical offset (relative to the font size) for the markers
  152. created for a scatter plot legend entry. 0.0 is at the base the
  153. legend text, and 1.0 is at the top. To draw all markers at the
  154. same height, set to ``[0.5]``. Default is ``[0.375, 0.5, 0.3125]``.
  155. markerscale : None or int or float
  156. The relative size of legend markers compared with the originally
  157. drawn ones.
  158. Default is ``None``, which means using :rc:`legend.markerscale`.
  159. markerfirst : bool
  160. If *True*, legend marker is placed to the left of the legend label.
  161. If *False*, legend marker is placed to the right of the legend
  162. label.
  163. Default is *True*.
  164. frameon : None or bool
  165. Whether the legend should be drawn on a patch (frame).
  166. Default is ``None``, which means using :rc:`legend.frameon`.
  167. fancybox : None or bool
  168. Whether round edges should be enabled around the `~.FancyBboxPatch` which
  169. makes up the legend's background.
  170. Default is ``None``, which means using :rc:`legend.fancybox`.
  171. shadow : None or bool
  172. Whether to draw a shadow behind the legend.
  173. Default is ``None``, which means using :rc:`legend.shadow`.
  174. framealpha : None or float
  175. The alpha transparency of the legend's background.
  176. Default is ``None``, which means using :rc:`legend.framealpha`.
  177. If *shadow* is activated and *framealpha* is ``None``, the default value is
  178. ignored.
  179. facecolor : None or "inherit" or color
  180. The legend's background color.
  181. Default is ``None``, which means using :rc:`legend.facecolor`.
  182. If ``"inherit"``, use :rc:`axes.facecolor`.
  183. edgecolor : None or "inherit" or color
  184. The legend's background patch edge color.
  185. Default is ``None``, which means using :rc:`legend.edgecolor`.
  186. If ``"inherit"``, use take :rc:`axes.edgecolor`.
  187. mode : {"expand", None}
  188. If *mode* is set to ``"expand"`` the legend will be horizontally
  189. expanded to fill the axes area (or `bbox_to_anchor` if defines
  190. the legend's size).
  191. bbox_transform : None or :class:`matplotlib.transforms.Transform`
  192. The transform for the bounding box (`bbox_to_anchor`). For a value
  193. of ``None`` (default) the Axes'
  194. :data:`~matplotlib.axes.Axes.transAxes` transform will be used.
  195. title : str or None
  196. The legend's title. Default is no title (``None``).
  197. title_fontsize: str or None
  198. The fontsize of the legend's title. Default is the default fontsize.
  199. borderpad : float or None
  200. The fractional whitespace inside the legend border, in font-size units.
  201. Default is ``None``, which means using :rc:`legend.borderpad`.
  202. labelspacing : float or None
  203. The vertical space between the legend entries, in font-size units.
  204. Default is ``None``, which means using :rc:`legend.labelspacing`.
  205. handlelength : float or None
  206. The length of the legend handles, in font-size units.
  207. Default is ``None``, which means using :rc:`legend.handlelength`.
  208. handletextpad : float or None
  209. The pad between the legend handle and text, in font-size units.
  210. Default is ``None``, which means using :rc:`legend.handletextpad`.
  211. borderaxespad : float or None
  212. The pad between the axes and legend border, in font-size units.
  213. Default is ``None``, which means using :rc:`legend.borderaxespad`.
  214. columnspacing : float or None
  215. The spacing between columns, in font-size units.
  216. Default is ``None``, which means using :rc:`legend.columnspacing`.
  217. handler_map : dict or None
  218. The custom dictionary mapping instances or types to a legend
  219. handler. This `handler_map` updates the default handler map
  220. found at :func:`matplotlib.legend.Legend.get_legend_handler_map`.
  221. '''
  222. docstring.interpd.update(_legend_kw_doc=_legend_kw_doc)
  223. class Legend(Artist):
  224. """
  225. Place a legend on the axes at location loc.
  226. """
  227. codes = {'best': 0, # only implemented for axes legends
  228. 'upper right': 1,
  229. 'upper left': 2,
  230. 'lower left': 3,
  231. 'lower right': 4,
  232. 'right': 5,
  233. 'center left': 6,
  234. 'center right': 7,
  235. 'lower center': 8,
  236. 'upper center': 9,
  237. 'center': 10,
  238. }
  239. zorder = 5
  240. def __str__(self):
  241. return "Legend"
  242. @docstring.dedent_interpd
  243. def __init__(self, parent, handles, labels,
  244. loc=None,
  245. numpoints=None, # the number of points in the legend line
  246. markerscale=None, # the relative size of legend markers
  247. # vs. original
  248. markerfirst=True, # controls ordering (left-to-right) of
  249. # legend marker and label
  250. scatterpoints=None, # number of scatter points
  251. scatteryoffsets=None,
  252. prop=None, # properties for the legend texts
  253. fontsize=None, # keyword to set font size directly
  254. # spacing & pad defined as a fraction of the font-size
  255. borderpad=None, # the whitespace inside the legend border
  256. labelspacing=None, # the vertical space between the legend
  257. # entries
  258. handlelength=None, # the length of the legend handles
  259. handleheight=None, # the height of the legend handles
  260. handletextpad=None, # the pad between the legend handle
  261. # and text
  262. borderaxespad=None, # the pad between the axes and legend
  263. # border
  264. columnspacing=None, # spacing between columns
  265. ncol=1, # number of columns
  266. mode=None, # mode for horizontal distribution of columns.
  267. # None, "expand"
  268. fancybox=None, # True use a fancy box, false use a rounded
  269. # box, none use rc
  270. shadow=None,
  271. title=None, # set a title for the legend
  272. title_fontsize=None, # set to ax.fontsize if None
  273. framealpha=None, # set frame alpha
  274. edgecolor=None, # frame patch edgecolor
  275. facecolor=None, # frame patch facecolor
  276. bbox_to_anchor=None, # bbox that the legend will be anchored.
  277. bbox_transform=None, # transform for the bbox
  278. frameon=None, # draw frame
  279. handler_map=None,
  280. ):
  281. """
  282. Parameters
  283. ----------
  284. parent : `~matplotlib.axes.Axes` or `.Figure`
  285. The artist that contains the legend.
  286. handles : list of `.Artist`
  287. A list of Artists (lines, patches) to be added to the legend.
  288. labels : list of str
  289. A list of labels to show next to the artists. The length of handles
  290. and labels should be the same. If they are not, they are truncated
  291. to the smaller of both lengths.
  292. Other Parameters
  293. ----------------
  294. %(_legend_kw_doc)s
  295. Notes
  296. -----
  297. Users can specify any arbitrary location for the legend using the
  298. *bbox_to_anchor* keyword argument. *bbox_to_anchor* can be a
  299. `.BboxBase` (or derived therefrom) or a tuple of 2 or 4 floats.
  300. See :meth:`set_bbox_to_anchor` for more detail.
  301. The legend location can be specified by setting *loc* with a tuple of
  302. 2 floats, which is interpreted as the lower-left corner of the legend
  303. in the normalized axes coordinate.
  304. """
  305. # local import only to avoid circularity
  306. from matplotlib.axes import Axes
  307. from matplotlib.figure import Figure
  308. Artist.__init__(self)
  309. if prop is None:
  310. if fontsize is not None:
  311. self.prop = FontProperties(size=fontsize)
  312. else:
  313. self.prop = FontProperties(size=rcParams["legend.fontsize"])
  314. elif isinstance(prop, dict):
  315. self.prop = FontProperties(**prop)
  316. if "size" not in prop:
  317. self.prop.set_size(rcParams["legend.fontsize"])
  318. else:
  319. self.prop = prop
  320. self._fontsize = self.prop.get_size_in_points()
  321. self.texts = []
  322. self.legendHandles = []
  323. self._legend_title_box = None
  324. #: A dictionary with the extra handler mappings for this Legend
  325. #: instance.
  326. self._custom_handler_map = handler_map
  327. locals_view = locals()
  328. for name in ["numpoints", "markerscale", "shadow", "columnspacing",
  329. "scatterpoints", "handleheight", 'borderpad',
  330. 'labelspacing', 'handlelength', 'handletextpad',
  331. 'borderaxespad']:
  332. if locals_view[name] is None:
  333. value = rcParams["legend." + name]
  334. else:
  335. value = locals_view[name]
  336. setattr(self, name, value)
  337. del locals_view
  338. # trim handles and labels if illegal label...
  339. _lab, _hand = [], []
  340. for label, handle in zip(labels, handles):
  341. if isinstance(label, str) and label.startswith('_'):
  342. cbook._warn_external('The handle {!r} has a label of {!r} '
  343. 'which cannot be automatically added to'
  344. ' the legend.'.format(handle, label))
  345. else:
  346. _lab.append(label)
  347. _hand.append(handle)
  348. labels, handles = _lab, _hand
  349. handles = list(handles)
  350. if len(handles) < 2:
  351. ncol = 1
  352. self._ncol = ncol
  353. if self.numpoints <= 0:
  354. raise ValueError("numpoints must be > 0; it was %d" % numpoints)
  355. # introduce y-offset for handles of the scatter plot
  356. if scatteryoffsets is None:
  357. self._scatteryoffsets = np.array([3. / 8., 4. / 8., 2.5 / 8.])
  358. else:
  359. self._scatteryoffsets = np.asarray(scatteryoffsets)
  360. reps = self.scatterpoints // len(self._scatteryoffsets) + 1
  361. self._scatteryoffsets = np.tile(self._scatteryoffsets,
  362. reps)[:self.scatterpoints]
  363. # _legend_box is an OffsetBox instance that contains all
  364. # legend items and will be initialized from _init_legend_box()
  365. # method.
  366. self._legend_box = None
  367. if isinstance(parent, Axes):
  368. self.isaxes = True
  369. self.axes = parent
  370. self.set_figure(parent.figure)
  371. elif isinstance(parent, Figure):
  372. self.isaxes = False
  373. self.set_figure(parent)
  374. else:
  375. raise TypeError("Legend needs either Axes or Figure as parent")
  376. self.parent = parent
  377. self._loc_used_default = loc is None
  378. if loc is None:
  379. loc = rcParams["legend.loc"]
  380. if not self.isaxes and loc in [0, 'best']:
  381. loc = 'upper right'
  382. if isinstance(loc, str):
  383. if loc not in self.codes:
  384. if self.isaxes:
  385. cbook.warn_deprecated(
  386. "3.1", message="Unrecognized location {!r}. Falling "
  387. "back on 'best'; valid locations are\n\t{}\n"
  388. "This will raise an exception %(removal)s."
  389. .format(loc, '\n\t'.join(self.codes)))
  390. loc = 0
  391. else:
  392. cbook.warn_deprecated(
  393. "3.1", message="Unrecognized location {!r}. Falling "
  394. "back on 'upper right'; valid locations are\n\t{}\n'"
  395. "This will raise an exception %(removal)s."
  396. .format(loc, '\n\t'.join(self.codes)))
  397. loc = 1
  398. else:
  399. loc = self.codes[loc]
  400. if not self.isaxes and loc == 0:
  401. cbook.warn_deprecated(
  402. "3.1", message="Automatic legend placement (loc='best') not "
  403. "implemented for figure legend. Falling back on 'upper "
  404. "right'. This will raise an exception %(removal)s.")
  405. loc = 1
  406. self._mode = mode
  407. self.set_bbox_to_anchor(bbox_to_anchor, bbox_transform)
  408. # We use FancyBboxPatch to draw a legend frame. The location
  409. # and size of the box will be updated during the drawing time.
  410. if facecolor is None:
  411. facecolor = rcParams["legend.facecolor"]
  412. if facecolor == 'inherit':
  413. facecolor = rcParams["axes.facecolor"]
  414. if edgecolor is None:
  415. edgecolor = rcParams["legend.edgecolor"]
  416. if edgecolor == 'inherit':
  417. edgecolor = rcParams["axes.edgecolor"]
  418. self.legendPatch = FancyBboxPatch(
  419. xy=(0.0, 0.0), width=1., height=1.,
  420. facecolor=facecolor,
  421. edgecolor=edgecolor,
  422. mutation_scale=self._fontsize,
  423. snap=True
  424. )
  425. # The width and height of the legendPatch will be set (in the
  426. # draw()) to the length that includes the padding. Thus we set
  427. # pad=0 here.
  428. if fancybox is None:
  429. fancybox = rcParams["legend.fancybox"]
  430. if fancybox:
  431. self.legendPatch.set_boxstyle("round", pad=0,
  432. rounding_size=0.2)
  433. else:
  434. self.legendPatch.set_boxstyle("square", pad=0)
  435. self._set_artist_props(self.legendPatch)
  436. self._drawFrame = frameon
  437. if frameon is None:
  438. self._drawFrame = rcParams["legend.frameon"]
  439. # init with null renderer
  440. self._init_legend_box(handles, labels, markerfirst)
  441. # If shadow is activated use framealpha if not
  442. # explicitly passed. See Issue 8943
  443. if framealpha is None:
  444. if shadow:
  445. self.get_frame().set_alpha(1)
  446. else:
  447. self.get_frame().set_alpha(rcParams["legend.framealpha"])
  448. else:
  449. self.get_frame().set_alpha(framealpha)
  450. tmp = self._loc_used_default
  451. self._set_loc(loc)
  452. self._loc_used_default = tmp # ignore changes done by _set_loc
  453. # figure out title fontsize:
  454. if title_fontsize is None:
  455. title_fontsize = rcParams['legend.title_fontsize']
  456. tprop = FontProperties(size=title_fontsize)
  457. self.set_title(title, prop=tprop)
  458. self._draggable = None
  459. def _set_artist_props(self, a):
  460. """
  461. Set the boilerplate props for artists added to axes.
  462. """
  463. a.set_figure(self.figure)
  464. if self.isaxes:
  465. # a.set_axes(self.axes)
  466. a.axes = self.axes
  467. a.set_transform(self.get_transform())
  468. def _set_loc(self, loc):
  469. # find_offset function will be provided to _legend_box and
  470. # _legend_box will draw itself at the location of the return
  471. # value of the find_offset.
  472. self._loc_used_default = False
  473. self._loc_real = loc
  474. self.stale = True
  475. self._legend_box.set_offset(self._findoffset)
  476. def _get_loc(self):
  477. return self._loc_real
  478. _loc = property(_get_loc, _set_loc)
  479. def _findoffset(self, width, height, xdescent, ydescent, renderer):
  480. "Helper function to locate the legend."
  481. if self._loc == 0: # "best".
  482. x, y = self._find_best_position(width, height, renderer)
  483. elif self._loc in Legend.codes.values(): # Fixed location.
  484. bbox = Bbox.from_bounds(0, 0, width, height)
  485. x, y = self._get_anchored_bbox(self._loc, bbox,
  486. self.get_bbox_to_anchor(),
  487. renderer)
  488. else: # Axes or figure coordinates.
  489. fx, fy = self._loc
  490. bbox = self.get_bbox_to_anchor()
  491. x, y = bbox.x0 + bbox.width * fx, bbox.y0 + bbox.height * fy
  492. return x + xdescent, y + ydescent
  493. @allow_rasterization
  494. def draw(self, renderer):
  495. "Draw everything that belongs to the legend."
  496. if not self.get_visible():
  497. return
  498. renderer.open_group('legend', gid=self.get_gid())
  499. fontsize = renderer.points_to_pixels(self._fontsize)
  500. # if mode == fill, set the width of the legend_box to the
  501. # width of the parent (minus pads)
  502. if self._mode in ["expand"]:
  503. pad = 2 * (self.borderaxespad + self.borderpad) * fontsize
  504. self._legend_box.set_width(self.get_bbox_to_anchor().width - pad)
  505. # update the location and size of the legend. This needs to
  506. # be done in any case to clip the figure right.
  507. bbox = self._legend_box.get_window_extent(renderer)
  508. self.legendPatch.set_bounds(bbox.x0, bbox.y0,
  509. bbox.width, bbox.height)
  510. self.legendPatch.set_mutation_scale(fontsize)
  511. if self._drawFrame:
  512. if self.shadow:
  513. shadow = Shadow(self.legendPatch, 2, -2)
  514. shadow.draw(renderer)
  515. self.legendPatch.draw(renderer)
  516. self._legend_box.draw(renderer)
  517. renderer.close_group('legend')
  518. self.stale = False
  519. def _approx_text_height(self, renderer=None):
  520. """
  521. Return the approximate height of the text. This is used to place
  522. the legend handle.
  523. """
  524. if renderer is None:
  525. return self._fontsize
  526. else:
  527. return renderer.points_to_pixels(self._fontsize)
  528. # _default_handler_map defines the default mapping between plot
  529. # elements and the legend handlers.
  530. _default_handler_map = {
  531. StemContainer: legend_handler.HandlerStem(),
  532. ErrorbarContainer: legend_handler.HandlerErrorbar(),
  533. Line2D: legend_handler.HandlerLine2D(),
  534. Patch: legend_handler.HandlerPatch(),
  535. LineCollection: legend_handler.HandlerLineCollection(),
  536. RegularPolyCollection: legend_handler.HandlerRegularPolyCollection(),
  537. CircleCollection: legend_handler.HandlerCircleCollection(),
  538. BarContainer: legend_handler.HandlerPatch(
  539. update_func=legend_handler.update_from_first_child),
  540. tuple: legend_handler.HandlerTuple(),
  541. PathCollection: legend_handler.HandlerPathCollection(),
  542. PolyCollection: legend_handler.HandlerPolyCollection()
  543. }
  544. # (get|set|update)_default_handler_maps are public interfaces to
  545. # modify the default handler map.
  546. @classmethod
  547. def get_default_handler_map(cls):
  548. """
  549. A class method that returns the default handler map.
  550. """
  551. return cls._default_handler_map
  552. @classmethod
  553. def set_default_handler_map(cls, handler_map):
  554. """
  555. A class method to set the default handler map.
  556. """
  557. cls._default_handler_map = handler_map
  558. @classmethod
  559. def update_default_handler_map(cls, handler_map):
  560. """
  561. A class method to update the default handler map.
  562. """
  563. cls._default_handler_map.update(handler_map)
  564. def get_legend_handler_map(self):
  565. """
  566. Return the handler map.
  567. """
  568. default_handler_map = self.get_default_handler_map()
  569. if self._custom_handler_map:
  570. hm = default_handler_map.copy()
  571. hm.update(self._custom_handler_map)
  572. return hm
  573. else:
  574. return default_handler_map
  575. @staticmethod
  576. def get_legend_handler(legend_handler_map, orig_handle):
  577. """
  578. Return a legend handler from *legend_handler_map* that
  579. corresponds to *orig_handler*.
  580. *legend_handler_map* should be a dictionary object (that is
  581. returned by the get_legend_handler_map method).
  582. It first checks if the *orig_handle* itself is a key in the
  583. *legend_handler_map* and return the associated value.
  584. Otherwise, it checks for each of the classes in its
  585. method-resolution-order. If no matching key is found, it
  586. returns ``None``.
  587. """
  588. try:
  589. return legend_handler_map[orig_handle]
  590. except (TypeError, KeyError): # TypeError if unhashable.
  591. pass
  592. for handle_type in type(orig_handle).mro():
  593. try:
  594. return legend_handler_map[handle_type]
  595. except KeyError:
  596. pass
  597. return None
  598. def _init_legend_box(self, handles, labels, markerfirst=True):
  599. """
  600. Initialize the legend_box. The legend_box is an instance of
  601. the OffsetBox, which is packed with legend handles and
  602. texts. Once packed, their location is calculated during the
  603. drawing time.
  604. """
  605. fontsize = self._fontsize
  606. # legend_box is a HPacker, horizontally packed with
  607. # columns. Each column is a VPacker, vertically packed with
  608. # legend items. Each legend item is HPacker packed with
  609. # legend handleBox and labelBox. handleBox is an instance of
  610. # offsetbox.DrawingArea which contains legend handle. labelBox
  611. # is an instance of offsetbox.TextArea which contains legend
  612. # text.
  613. text_list = [] # the list of text instances
  614. handle_list = [] # the list of text instances
  615. handles_and_labels = []
  616. label_prop = dict(verticalalignment='baseline',
  617. horizontalalignment='left',
  618. fontproperties=self.prop,
  619. )
  620. # The approximate height and descent of text. These values are
  621. # only used for plotting the legend handle.
  622. descent = 0.35 * self._approx_text_height() * (self.handleheight - 0.7)
  623. # 0.35 and 0.7 are just heuristic numbers and may need to be improved.
  624. height = self._approx_text_height() * self.handleheight - descent
  625. # each handle needs to be drawn inside a box of (x, y, w, h) =
  626. # (0, -descent, width, height). And their coordinates should
  627. # be given in the display coordinates.
  628. # The transformation of each handle will be automatically set
  629. # to self.get_transform(). If the artist does not use its
  630. # default transform (e.g., Collections), you need to
  631. # manually set their transform to the self.get_transform().
  632. legend_handler_map = self.get_legend_handler_map()
  633. for orig_handle, lab in zip(handles, labels):
  634. handler = self.get_legend_handler(legend_handler_map, orig_handle)
  635. if handler is None:
  636. cbook._warn_external(
  637. "Legend does not support {!r} instances.\nA proxy artist "
  638. "may be used instead.\nSee: "
  639. "http://matplotlib.org/users/legend_guide.html"
  640. "#creating-artists-specifically-for-adding-to-the-legend-"
  641. "aka-proxy-artists".format(orig_handle))
  642. # We don't have a handle for this artist, so we just defer
  643. # to None.
  644. handle_list.append(None)
  645. else:
  646. textbox = TextArea(lab, textprops=label_prop,
  647. multilinebaseline=True,
  648. minimumdescent=True)
  649. handlebox = DrawingArea(width=self.handlelength * fontsize,
  650. height=height,
  651. xdescent=0., ydescent=descent)
  652. text_list.append(textbox._text)
  653. # Create the artist for the legend which represents the
  654. # original artist/handle.
  655. handle_list.append(handler.legend_artist(self, orig_handle,
  656. fontsize, handlebox))
  657. handles_and_labels.append((handlebox, textbox))
  658. if handles_and_labels:
  659. # We calculate number of rows in each column. The first
  660. # (num_largecol) columns will have (nrows+1) rows, and remaining
  661. # (num_smallcol) columns will have (nrows) rows.
  662. ncol = min(self._ncol, len(handles_and_labels))
  663. nrows, num_largecol = divmod(len(handles_and_labels), ncol)
  664. num_smallcol = ncol - num_largecol
  665. # starting index of each column and number of rows in it.
  666. rows_per_col = [nrows + 1] * num_largecol + [nrows] * num_smallcol
  667. start_idxs = np.concatenate([[0], np.cumsum(rows_per_col)[:-1]])
  668. cols = zip(start_idxs, rows_per_col)
  669. else:
  670. cols = []
  671. columnbox = []
  672. for i0, di in cols:
  673. # pack handleBox and labelBox into itemBox
  674. itemBoxes = [HPacker(pad=0,
  675. sep=self.handletextpad * fontsize,
  676. children=[h, t] if markerfirst else [t, h],
  677. align="baseline")
  678. for h, t in handles_and_labels[i0:i0 + di]]
  679. # minimumdescent=False for the text of the last row of the column
  680. if markerfirst:
  681. itemBoxes[-1].get_children()[1].set_minimumdescent(False)
  682. else:
  683. itemBoxes[-1].get_children()[0].set_minimumdescent(False)
  684. # pack columnBox
  685. alignment = "baseline" if markerfirst else "right"
  686. columnbox.append(VPacker(pad=0,
  687. sep=self.labelspacing * fontsize,
  688. align=alignment,
  689. children=itemBoxes))
  690. mode = "expand" if self._mode == "expand" else "fixed"
  691. sep = self.columnspacing * fontsize
  692. self._legend_handle_box = HPacker(pad=0,
  693. sep=sep, align="baseline",
  694. mode=mode,
  695. children=columnbox)
  696. self._legend_title_box = TextArea("")
  697. self._legend_box = VPacker(pad=self.borderpad * fontsize,
  698. sep=self.labelspacing * fontsize,
  699. align="center",
  700. children=[self._legend_title_box,
  701. self._legend_handle_box])
  702. self._legend_box.set_figure(self.figure)
  703. self.texts = text_list
  704. self.legendHandles = handle_list
  705. def _auto_legend_data(self):
  706. """
  707. Returns list of vertices and extents covered by the plot.
  708. Returns a two long list.
  709. First element is a list of (x, y) vertices (in
  710. display-coordinates) covered by all the lines and line
  711. collections, in the legend's handles.
  712. Second element is a list of bounding boxes for all the patches in
  713. the legend's handles.
  714. """
  715. # should always hold because function is only called internally
  716. assert self.isaxes
  717. ax = self.parent
  718. bboxes = []
  719. lines = []
  720. offsets = []
  721. for handle in ax.lines:
  722. assert isinstance(handle, Line2D)
  723. path = handle.get_path()
  724. trans = handle.get_transform()
  725. tpath = trans.transform_path(path)
  726. lines.append(tpath)
  727. for handle in ax.patches:
  728. assert isinstance(handle, Patch)
  729. if isinstance(handle, Rectangle):
  730. transform = handle.get_data_transform()
  731. bboxes.append(handle.get_bbox().transformed(transform))
  732. else:
  733. transform = handle.get_transform()
  734. bboxes.append(handle.get_path().get_extents(transform))
  735. for handle in ax.collections:
  736. transform, transOffset, hoffsets, paths = handle._prepare_points()
  737. if len(hoffsets):
  738. for offset in transOffset.transform(hoffsets):
  739. offsets.append(offset)
  740. try:
  741. vertices = np.concatenate([l.vertices for l in lines])
  742. except ValueError:
  743. vertices = np.array([])
  744. return [vertices, bboxes, lines, offsets]
  745. def draw_frame(self, b):
  746. '''
  747. Set draw frame to b.
  748. Parameters
  749. ----------
  750. b : bool
  751. '''
  752. self.set_frame_on(b)
  753. def get_children(self):
  754. 'Return a list of child artists.'
  755. children = []
  756. if self._legend_box:
  757. children.append(self._legend_box)
  758. children.append(self.get_frame())
  759. return children
  760. def get_frame(self):
  761. '''
  762. Return the `~.patches.Rectangle` instances used to frame the legend.
  763. '''
  764. return self.legendPatch
  765. def get_lines(self):
  766. 'Return a list of `~.lines.Line2D` instances in the legend.'
  767. return [h for h in self.legendHandles if isinstance(h, Line2D)]
  768. def get_patches(self):
  769. 'Return a list of `~.patches.Patch` instances in the legend.'
  770. return silent_list('Patch',
  771. [h for h in self.legendHandles
  772. if isinstance(h, Patch)])
  773. def get_texts(self):
  774. 'Return a list of `~.text.Text` instances in the legend.'
  775. return silent_list('Text', self.texts)
  776. def set_title(self, title, prop=None):
  777. """
  778. Set the legend title. Fontproperties can be optionally set
  779. with *prop* parameter.
  780. """
  781. self._legend_title_box._text.set_text(title)
  782. if title:
  783. self._legend_title_box._text.set_visible(True)
  784. self._legend_title_box.set_visible(True)
  785. else:
  786. self._legend_title_box._text.set_visible(False)
  787. self._legend_title_box.set_visible(False)
  788. if prop is not None:
  789. if isinstance(prop, dict):
  790. prop = FontProperties(**prop)
  791. self._legend_title_box._text.set_fontproperties(prop)
  792. self.stale = True
  793. def get_title(self):
  794. 'Return the `.Text` instance for the legend title.'
  795. return self._legend_title_box._text
  796. def get_window_extent(self, renderer=None):
  797. 'Return extent of the legend.'
  798. if renderer is None:
  799. renderer = self.figure._cachedRenderer
  800. return self._legend_box.get_window_extent(renderer=renderer)
  801. def get_tightbbox(self, renderer):
  802. """
  803. Like `.Legend.get_window_extent`, but uses the box for the legend.
  804. Parameters
  805. ----------
  806. renderer : `.RendererBase` instance
  807. renderer that will be used to draw the figures (i.e.
  808. ``fig.canvas.get_renderer()``)
  809. Returns
  810. -------
  811. `.BboxBase` : containing the bounding box in figure pixel co-ordinates.
  812. """
  813. return self._legend_box.get_window_extent(renderer)
  814. def get_frame_on(self):
  815. """Get whether the legend box patch is drawn."""
  816. return self._drawFrame
  817. def set_frame_on(self, b):
  818. """
  819. Set whether the legend box patch is drawn.
  820. Parameters
  821. ----------
  822. b : bool
  823. """
  824. self._drawFrame = b
  825. self.stale = True
  826. def get_bbox_to_anchor(self):
  827. """Return the bbox that the legend will be anchored to."""
  828. if self._bbox_to_anchor is None:
  829. return self.parent.bbox
  830. else:
  831. return self._bbox_to_anchor
  832. def set_bbox_to_anchor(self, bbox, transform=None):
  833. """
  834. Set the bbox that the legend will be anchored to.
  835. *bbox* can be
  836. - A `.BboxBase` instance
  837. - A tuple of ``(left, bottom, width, height)`` in the given transform
  838. (normalized axes coordinate if None)
  839. - A tuple of ``(left, bottom)`` where the width and height will be
  840. assumed to be zero.
  841. """
  842. if bbox is None:
  843. self._bbox_to_anchor = None
  844. return
  845. elif isinstance(bbox, BboxBase):
  846. self._bbox_to_anchor = bbox
  847. else:
  848. try:
  849. l = len(bbox)
  850. except TypeError:
  851. raise ValueError("Invalid argument for bbox : %s" % str(bbox))
  852. if l == 2:
  853. bbox = [bbox[0], bbox[1], 0, 0]
  854. self._bbox_to_anchor = Bbox.from_bounds(*bbox)
  855. if transform is None:
  856. transform = BboxTransformTo(self.parent.bbox)
  857. self._bbox_to_anchor = TransformedBbox(self._bbox_to_anchor,
  858. transform)
  859. self.stale = True
  860. def _get_anchored_bbox(self, loc, bbox, parentbbox, renderer):
  861. """
  862. Place the *bbox* inside the *parentbbox* according to a given
  863. location code. Return the (x, y) coordinate of the bbox.
  864. - loc: a location code in range(1, 11).
  865. This corresponds to the possible values for self._loc, excluding
  866. "best".
  867. - bbox: bbox to be placed, display coordinate units.
  868. - parentbbox: a parent box which will contain the bbox. In
  869. display coordinates.
  870. """
  871. assert loc in range(1, 11) # called only internally
  872. BEST, UR, UL, LL, LR, R, CL, CR, LC, UC, C = range(11)
  873. anchor_coefs = {UR: "NE",
  874. UL: "NW",
  875. LL: "SW",
  876. LR: "SE",
  877. R: "E",
  878. CL: "W",
  879. CR: "E",
  880. LC: "S",
  881. UC: "N",
  882. C: "C"}
  883. c = anchor_coefs[loc]
  884. fontsize = renderer.points_to_pixels(self._fontsize)
  885. container = parentbbox.padded(-(self.borderaxespad) * fontsize)
  886. anchored_box = bbox.anchored(c, container=container)
  887. return anchored_box.x0, anchored_box.y0
  888. def _find_best_position(self, width, height, renderer, consider=None):
  889. """
  890. Determine the best location to place the legend.
  891. *consider* is a list of ``(x, y)`` pairs to consider as a potential
  892. lower-left corner of the legend. All are display coords.
  893. """
  894. # should always hold because function is only called internally
  895. assert self.isaxes
  896. start_time = time.perf_counter()
  897. verts, bboxes, lines, offsets = self._auto_legend_data()
  898. bbox = Bbox.from_bounds(0, 0, width, height)
  899. if consider is None:
  900. consider = [self._get_anchored_bbox(x, bbox,
  901. self.get_bbox_to_anchor(),
  902. renderer)
  903. for x in range(1, len(self.codes))]
  904. candidates = []
  905. for idx, (l, b) in enumerate(consider):
  906. legendBox = Bbox.from_bounds(l, b, width, height)
  907. badness = 0
  908. # XXX TODO: If markers are present, it would be good to
  909. # take them into account when checking vertex overlaps in
  910. # the next line.
  911. badness = (legendBox.count_contains(verts)
  912. + legendBox.count_contains(offsets)
  913. + legendBox.count_overlaps(bboxes)
  914. + sum(line.intersects_bbox(legendBox, filled=False)
  915. for line in lines))
  916. if badness == 0:
  917. return l, b
  918. # Include the index to favor lower codes in case of a tie.
  919. candidates.append((badness, idx, (l, b)))
  920. _, _, (l, b) = min(candidates)
  921. if self._loc_used_default and time.perf_counter() - start_time > 1:
  922. cbook._warn_external(
  923. 'Creating legend with loc="best" can be slow with large '
  924. 'amounts of data.')
  925. return l, b
  926. def contains(self, event):
  927. inside, info = self._default_contains(event)
  928. if inside is not None:
  929. return inside, info
  930. return self.legendPatch.contains(event)
  931. def set_draggable(self, state, use_blit=False, update='loc'):
  932. """
  933. Enable or disable mouse dragging support of the legend.
  934. Parameters
  935. ----------
  936. state : bool
  937. Whether mouse dragging is enabled.
  938. use_blit : bool, optional
  939. Use blitting for faster image composition. For details see
  940. :ref:`func-animation`.
  941. update : {'loc', 'bbox'}, optional
  942. The legend parameter to be changed when dragged:
  943. - 'loc': update the *loc* parameter of the legend
  944. - 'bbox': update the *bbox_to_anchor* parameter of the legend
  945. Returns
  946. -------
  947. If *state* is ``True`` this returns the `~.DraggableLegend` helper
  948. instance. Otherwise this returns ``None``.
  949. """
  950. if state:
  951. if self._draggable is None:
  952. self._draggable = DraggableLegend(self,
  953. use_blit,
  954. update=update)
  955. else:
  956. if self._draggable is not None:
  957. self._draggable.disconnect()
  958. self._draggable = None
  959. return self._draggable
  960. def get_draggable(self):
  961. """Return ``True`` if the legend is draggable, ``False`` otherwise."""
  962. return self._draggable is not None
  963. # Helper functions to parse legend arguments for both `figure.legend` and
  964. # `axes.legend`:
  965. def _get_legend_handles(axs, legend_handler_map=None):
  966. """
  967. Return a generator of artists that can be used as handles in
  968. a legend.
  969. """
  970. handles_original = []
  971. for ax in axs:
  972. handles_original += (ax.lines + ax.patches +
  973. ax.collections + ax.containers)
  974. # support parasite axes:
  975. if hasattr(ax, 'parasites'):
  976. for axx in ax.parasites:
  977. handles_original += (axx.lines + axx.patches +
  978. axx.collections + axx.containers)
  979. handler_map = Legend.get_default_handler_map()
  980. if legend_handler_map is not None:
  981. handler_map = handler_map.copy()
  982. handler_map.update(legend_handler_map)
  983. has_handler = Legend.get_legend_handler
  984. for handle in handles_original:
  985. label = handle.get_label()
  986. if label != '_nolegend_' and has_handler(handler_map, handle):
  987. yield handle
  988. def _get_legend_handles_labels(axs, legend_handler_map=None):
  989. """
  990. Return handles and labels for legend, internal method.
  991. """
  992. handles = []
  993. labels = []
  994. for handle in _get_legend_handles(axs, legend_handler_map):
  995. label = handle.get_label()
  996. if label and not label.startswith('_'):
  997. handles.append(handle)
  998. labels.append(label)
  999. return handles, labels
  1000. def _parse_legend_args(axs, *args, handles=None, labels=None, **kwargs):
  1001. """
  1002. Get the handles and labels from the calls to either ``figure.legend``
  1003. or ``axes.legend``.
  1004. ``axs`` is a list of axes (to get legend artists from)
  1005. """
  1006. log = logging.getLogger(__name__)
  1007. handlers = kwargs.get('handler_map', {}) or {}
  1008. extra_args = ()
  1009. if (handles is not None or labels is not None) and args:
  1010. cbook._warn_external("You have mixed positional and keyword "
  1011. "arguments, some input may be discarded.")
  1012. # if got both handles and labels as kwargs, make same length
  1013. if handles and labels:
  1014. handles, labels = zip(*zip(handles, labels))
  1015. elif handles is not None and labels is None:
  1016. labels = [handle.get_label() for handle in handles]
  1017. elif labels is not None and handles is None:
  1018. # Get as many handles as there are labels.
  1019. handles = [handle for handle, label
  1020. in zip(_get_legend_handles(axs, handlers), labels)]
  1021. # No arguments - automatically detect labels and handles.
  1022. elif len(args) == 0:
  1023. handles, labels = _get_legend_handles_labels(axs, handlers)
  1024. if not handles:
  1025. log.warning('No handles with labels found to put in legend.')
  1026. # One argument. User defined labels - automatic handle detection.
  1027. elif len(args) == 1:
  1028. labels, = args
  1029. # Get as many handles as there are labels.
  1030. handles = [handle for handle, label
  1031. in zip(_get_legend_handles(axs, handlers), labels)]
  1032. # Two arguments:
  1033. # * user defined handles and labels
  1034. elif len(args) >= 2:
  1035. handles, labels = args[:2]
  1036. extra_args = args[2:]
  1037. else:
  1038. raise TypeError('Invalid arguments to legend.')
  1039. return handles, labels, extra_args, kwargs