legend.py 47 KB

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