legend.py 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371
  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 :ref:`legend guide
  8. <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 :ref`<legend_guide>` for more
  16. information.
  17. """
  18. import itertools
  19. import logging
  20. import numbers
  21. import time
  22. import numpy as np
  23. import matplotlib as mpl
  24. from matplotlib import _api, _docstring, cbook, colors, offsetbox
  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. StepPatch)
  31. from matplotlib.collections import (
  32. Collection, CircleCollection, LineCollection, PathCollection,
  33. PolyCollection, RegularPolyCollection)
  34. from matplotlib.text import Text
  35. from matplotlib.transforms import Bbox, BboxBase, TransformedBbox
  36. from matplotlib.transforms import BboxTransformTo, BboxTransformFrom
  37. from matplotlib.offsetbox import (
  38. AnchoredOffsetbox, DraggableOffsetBox,
  39. HPacker, VPacker,
  40. DrawingArea, TextArea,
  41. )
  42. from matplotlib.container import ErrorbarContainer, BarContainer, StemContainer
  43. from . import legend_handler
  44. class DraggableLegend(DraggableOffsetBox):
  45. def __init__(self, legend, use_blit=False, update="loc"):
  46. """
  47. Wrapper around a `.Legend` to support mouse dragging.
  48. Parameters
  49. ----------
  50. legend : `.Legend`
  51. The `.Legend` instance to wrap.
  52. use_blit : bool, optional
  53. Use blitting for faster image composition. For details see
  54. :ref:`func-animation`.
  55. update : {'loc', 'bbox'}, optional
  56. If "loc", update the *loc* parameter of the legend upon finalizing.
  57. If "bbox", update the *bbox_to_anchor* parameter.
  58. """
  59. self.legend = legend
  60. _api.check_in_list(["loc", "bbox"], update=update)
  61. self._update = update
  62. super().__init__(legend, legend._legend_box, use_blit=use_blit)
  63. def finalize_offset(self):
  64. if self._update == "loc":
  65. self._update_loc(self.get_loc_in_canvas())
  66. elif self._update == "bbox":
  67. self._update_bbox_to_anchor(self.get_loc_in_canvas())
  68. def _update_loc(self, loc_in_canvas):
  69. bbox = self.legend.get_bbox_to_anchor()
  70. # if bbox has zero width or height, the transformation is
  71. # ill-defined. Fall back to the default bbox_to_anchor.
  72. if bbox.width == 0 or bbox.height == 0:
  73. self.legend.set_bbox_to_anchor(None)
  74. bbox = self.legend.get_bbox_to_anchor()
  75. _bbox_transform = BboxTransformFrom(bbox)
  76. self.legend._loc = tuple(_bbox_transform.transform(loc_in_canvas))
  77. def _update_bbox_to_anchor(self, loc_in_canvas):
  78. loc_in_bbox = self.legend.axes.transAxes.transform(loc_in_canvas)
  79. self.legend.set_bbox_to_anchor(loc_in_bbox)
  80. _legend_kw_doc_base = """
  81. bbox_to_anchor : `.BboxBase`, 2-tuple, or 4-tuple of floats
  82. Box that is used to position the legend in conjunction with *loc*.
  83. Defaults to ``axes.bbox`` (if called as a method to `.Axes.legend`) or
  84. ``figure.bbox`` (if ``figure.legend``). This argument allows arbitrary
  85. placement of the legend.
  86. Bbox coordinates are interpreted in the coordinate system given by
  87. *bbox_transform*, with the default transform
  88. Axes or Figure coordinates, depending on which ``legend`` is called.
  89. If a 4-tuple or `.BboxBase` is given, then it specifies the bbox
  90. ``(x, y, width, height)`` that the legend is placed in.
  91. To put the legend in the best location in the bottom right
  92. quadrant of the Axes (or figure)::
  93. loc='best', bbox_to_anchor=(0.5, 0., 0.5, 0.5)
  94. A 2-tuple ``(x, y)`` places the corner of the legend specified by *loc* at
  95. x, y. For example, to put the legend's upper right-hand corner in the
  96. center of the Axes (or figure) the following keywords can be used::
  97. loc='upper right', bbox_to_anchor=(0.5, 0.5)
  98. ncols : int, default: 1
  99. The number of columns that the legend has.
  100. For backward compatibility, the spelling *ncol* is also supported
  101. but it is discouraged. If both are given, *ncols* takes precedence.
  102. prop : None or `~matplotlib.font_manager.FontProperties` or dict
  103. The font properties of the legend. If None (default), the current
  104. :data:`matplotlib.rcParams` will be used.
  105. fontsize : int or {'xx-small', 'x-small', 'small', 'medium', 'large', \
  106. 'x-large', 'xx-large'}
  107. The font size of the legend. If the value is numeric the size will be the
  108. absolute font size in points. String values are relative to the current
  109. default font size. This argument is only used if *prop* is not specified.
  110. labelcolor : str or list, default: :rc:`legend.labelcolor`
  111. The color of the text in the legend. Either a valid color string
  112. (for example, 'red'), or a list of color strings. The labelcolor can
  113. also be made to match the color of the line or marker using 'linecolor',
  114. 'markerfacecolor' (or 'mfc'), or 'markeredgecolor' (or 'mec').
  115. Labelcolor can be set globally using :rc:`legend.labelcolor`. If None,
  116. use :rc:`text.color`.
  117. numpoints : int, default: :rc:`legend.numpoints`
  118. The number of marker points in the legend when creating a legend
  119. entry for a `.Line2D` (line).
  120. scatterpoints : int, default: :rc:`legend.scatterpoints`
  121. The number of marker points in the legend when creating
  122. a legend entry for a `.PathCollection` (scatter plot).
  123. scatteryoffsets : iterable of floats, default: ``[0.375, 0.5, 0.3125]``
  124. The vertical offset (relative to the font size) for the markers
  125. created for a scatter plot legend entry. 0.0 is at the base the
  126. legend text, and 1.0 is at the top. To draw all markers at the
  127. same height, set to ``[0.5]``.
  128. markerscale : float, default: :rc:`legend.markerscale`
  129. The relative size of legend markers compared to the originally drawn ones.
  130. markerfirst : bool, default: True
  131. If *True*, legend marker is placed to the left of the legend label.
  132. If *False*, legend marker is placed to the right of the legend label.
  133. reverse : bool, default: False
  134. If *True*, the legend labels are displayed in reverse order from the input.
  135. If *False*, the legend labels are displayed in the same order as the input.
  136. .. versionadded:: 3.7
  137. frameon : bool, default: :rc:`legend.frameon`
  138. Whether the legend should be drawn on a patch (frame).
  139. fancybox : bool, default: :rc:`legend.fancybox`
  140. Whether round edges should be enabled around the `.FancyBboxPatch` which
  141. makes up the legend's background.
  142. shadow : None, bool or dict, default: :rc:`legend.shadow`
  143. Whether to draw a shadow behind the legend.
  144. The shadow can be configured using `.Patch` keywords.
  145. Customization via :rc:`legend.shadow` is currently not supported.
  146. framealpha : float, default: :rc:`legend.framealpha`
  147. The alpha transparency of the legend's background.
  148. If *shadow* is activated and *framealpha* is ``None``, the default value is
  149. ignored.
  150. facecolor : "inherit" or color, default: :rc:`legend.facecolor`
  151. The legend's background color.
  152. If ``"inherit"``, use :rc:`axes.facecolor`.
  153. edgecolor : "inherit" or color, default: :rc:`legend.edgecolor`
  154. The legend's background patch edge color.
  155. If ``"inherit"``, use :rc:`axes.edgecolor`.
  156. mode : {"expand", None}
  157. If *mode* is set to ``"expand"`` the legend will be horizontally
  158. expanded to fill the Axes area (or *bbox_to_anchor* if defines
  159. the legend's size).
  160. bbox_transform : None or `~matplotlib.transforms.Transform`
  161. The transform for the bounding box (*bbox_to_anchor*). For a value
  162. of ``None`` (default) the Axes'
  163. :data:`~matplotlib.axes.Axes.transAxes` transform will be used.
  164. title : str or None
  165. The legend's title. Default is no title (``None``).
  166. title_fontproperties : None or `~matplotlib.font_manager.FontProperties` or dict
  167. The font properties of the legend's title. If None (default), the
  168. *title_fontsize* argument will be used if present; if *title_fontsize* is
  169. also None, the current :rc:`legend.title_fontsize` will be used.
  170. title_fontsize : int or {'xx-small', 'x-small', 'small', 'medium', 'large', \
  171. 'x-large', 'xx-large'}, default: :rc:`legend.title_fontsize`
  172. The font size of the legend's title.
  173. Note: This cannot be combined with *title_fontproperties*. If you want
  174. to set the fontsize alongside other font properties, use the *size*
  175. parameter in *title_fontproperties*.
  176. alignment : {'center', 'left', 'right'}, default: 'center'
  177. The alignment of the legend title and the box of entries. The entries
  178. are aligned as a single block, so that markers always lined up.
  179. borderpad : float, default: :rc:`legend.borderpad`
  180. The fractional whitespace inside the legend border, in font-size units.
  181. labelspacing : float, default: :rc:`legend.labelspacing`
  182. The vertical space between the legend entries, in font-size units.
  183. handlelength : float, default: :rc:`legend.handlelength`
  184. The length of the legend handles, in font-size units.
  185. handleheight : float, default: :rc:`legend.handleheight`
  186. The height of the legend handles, in font-size units.
  187. handletextpad : float, default: :rc:`legend.handletextpad`
  188. The pad between the legend handle and text, in font-size units.
  189. borderaxespad : float, default: :rc:`legend.borderaxespad`
  190. The pad between the Axes and legend border, in font-size units.
  191. columnspacing : float, default: :rc:`legend.columnspacing`
  192. The spacing between columns, in font-size units.
  193. handler_map : dict or None
  194. The custom dictionary mapping instances or types to a legend
  195. handler. This *handler_map* updates the default handler map
  196. found at `matplotlib.legend.Legend.get_legend_handler_map`.
  197. draggable : bool, default: False
  198. Whether the legend can be dragged with the mouse.
  199. """
  200. _loc_doc_base = """
  201. loc : str or pair of floats, default: {default}
  202. The location of the legend.
  203. The strings ``'upper left'``, ``'upper right'``, ``'lower left'``,
  204. ``'lower right'`` place the legend at the corresponding corner of the
  205. {parent}.
  206. The strings ``'upper center'``, ``'lower center'``, ``'center left'``,
  207. ``'center right'`` place the legend at the center of the corresponding edge
  208. of the {parent}.
  209. The string ``'center'`` places the legend at the center of the {parent}.
  210. {best}
  211. The location can also be a 2-tuple giving the coordinates of the lower-left
  212. corner of the legend in {parent} coordinates (in which case *bbox_to_anchor*
  213. will be ignored).
  214. For back-compatibility, ``'center right'`` (but no other location) can also
  215. be spelled ``'right'``, and each "string" location can also be given as a
  216. numeric value:
  217. ================== =============
  218. Location String Location Code
  219. ================== =============
  220. 'best' (Axes only) 0
  221. 'upper right' 1
  222. 'upper left' 2
  223. 'lower left' 3
  224. 'lower right' 4
  225. 'right' 5
  226. 'center left' 6
  227. 'center right' 7
  228. 'lower center' 8
  229. 'upper center' 9
  230. 'center' 10
  231. ================== =============
  232. {outside}"""
  233. _loc_doc_best = """
  234. The string ``'best'`` places the legend at the location, among the nine
  235. locations defined so far, with the minimum overlap with other drawn
  236. artists. This option can be quite slow for plots with large amounts of
  237. data; your plotting speed may benefit from providing a specific location.
  238. """
  239. _legend_kw_axes_st = (
  240. _loc_doc_base.format(parent='axes', default=':rc:`legend.loc`',
  241. best=_loc_doc_best, outside='') +
  242. _legend_kw_doc_base)
  243. _docstring.interpd.register(_legend_kw_axes=_legend_kw_axes_st)
  244. _outside_doc = """
  245. If a figure is using the constrained layout manager, the string codes
  246. of the *loc* keyword argument can get better layout behaviour using the
  247. prefix 'outside'. There is ambiguity at the corners, so 'outside
  248. upper right' will make space for the legend above the rest of the
  249. axes in the layout, and 'outside right upper' will make space on the
  250. right side of the layout. In addition to the values of *loc*
  251. listed above, we have 'outside right upper', 'outside right lower',
  252. 'outside left upper', and 'outside left lower'. See
  253. :ref:`legend_guide` for more details.
  254. """
  255. _legend_kw_figure_st = (
  256. _loc_doc_base.format(parent='figure', default="'upper right'",
  257. best='', outside=_outside_doc) +
  258. _legend_kw_doc_base)
  259. _docstring.interpd.register(_legend_kw_figure=_legend_kw_figure_st)
  260. _legend_kw_both_st = (
  261. _loc_doc_base.format(parent='axes/figure',
  262. default=":rc:`legend.loc` for Axes, 'upper right' for Figure",
  263. best=_loc_doc_best, outside=_outside_doc) +
  264. _legend_kw_doc_base)
  265. _docstring.interpd.register(_legend_kw_doc=_legend_kw_both_st)
  266. _legend_kw_set_loc_st = (
  267. _loc_doc_base.format(parent='axes/figure',
  268. default=":rc:`legend.loc` for Axes, 'upper right' for Figure",
  269. best=_loc_doc_best, outside=_outside_doc))
  270. _docstring.interpd.register(_legend_kw_set_loc_doc=_legend_kw_set_loc_st)
  271. class Legend(Artist):
  272. """
  273. Place a legend on the figure/axes.
  274. """
  275. # 'best' is only implemented for Axes legends
  276. codes = {'best': 0, **AnchoredOffsetbox.codes}
  277. zorder = 5
  278. def __str__(self):
  279. return "Legend"
  280. @_docstring.interpd
  281. def __init__(
  282. self, parent, handles, labels,
  283. *,
  284. loc=None,
  285. numpoints=None, # number of points in the legend line
  286. markerscale=None, # relative size of legend markers vs. original
  287. markerfirst=True, # left/right ordering of legend marker and label
  288. reverse=False, # reverse ordering of legend marker and label
  289. scatterpoints=None, # number of scatter points
  290. scatteryoffsets=None,
  291. prop=None, # properties for the legend texts
  292. fontsize=None, # keyword to set font size directly
  293. labelcolor=None, # keyword to set the text color
  294. # spacing & pad defined as a fraction of the font-size
  295. borderpad=None, # whitespace inside the legend border
  296. labelspacing=None, # vertical space between the legend entries
  297. handlelength=None, # length of the legend handles
  298. handleheight=None, # height of the legend handles
  299. handletextpad=None, # pad between the legend handle and text
  300. borderaxespad=None, # pad between the Axes and legend border
  301. columnspacing=None, # spacing between columns
  302. ncols=1, # number of columns
  303. mode=None, # horizontal distribution of columns: None or "expand"
  304. fancybox=None, # True: fancy box, False: rounded box, None: rcParam
  305. shadow=None,
  306. title=None, # legend title
  307. title_fontsize=None, # legend title font size
  308. framealpha=None, # set frame alpha
  309. edgecolor=None, # frame patch edgecolor
  310. facecolor=None, # frame patch facecolor
  311. bbox_to_anchor=None, # bbox to which the legend will be anchored
  312. bbox_transform=None, # transform for the bbox
  313. frameon=None, # draw frame
  314. handler_map=None,
  315. title_fontproperties=None, # properties for the legend title
  316. alignment="center", # control the alignment within the legend box
  317. ncol=1, # synonym for ncols (backward compatibility)
  318. draggable=False # whether the legend can be dragged with the mouse
  319. ):
  320. """
  321. Parameters
  322. ----------
  323. parent : `~matplotlib.axes.Axes` or `.Figure`
  324. The artist that contains the legend.
  325. handles : list of (`.Artist` or tuple of `.Artist`)
  326. A list of Artists (lines, patches) to be added to the legend.
  327. labels : list of str
  328. A list of labels to show next to the artists. The length of handles
  329. and labels should be the same. If they are not, they are truncated
  330. to the length of the shorter list.
  331. Other Parameters
  332. ----------------
  333. %(_legend_kw_doc)s
  334. Attributes
  335. ----------
  336. legend_handles
  337. List of `.Artist` objects added as legend entries.
  338. .. versionadded:: 3.7
  339. """
  340. # local import only to avoid circularity
  341. from matplotlib.axes import Axes
  342. from matplotlib.figure import FigureBase
  343. super().__init__()
  344. if prop is None:
  345. self.prop = FontProperties(size=mpl._val_or_rc(fontsize, "legend.fontsize"))
  346. else:
  347. self.prop = FontProperties._from_any(prop)
  348. if isinstance(prop, dict) and "size" not in prop:
  349. self.prop.set_size(mpl.rcParams["legend.fontsize"])
  350. self._fontsize = self.prop.get_size_in_points()
  351. self.texts = []
  352. self.legend_handles = []
  353. self._legend_title_box = None
  354. #: A dictionary with the extra handler mappings for this Legend
  355. #: instance.
  356. self._custom_handler_map = handler_map
  357. self.numpoints = mpl._val_or_rc(numpoints, 'legend.numpoints')
  358. self.markerscale = mpl._val_or_rc(markerscale, 'legend.markerscale')
  359. self.scatterpoints = mpl._val_or_rc(scatterpoints, 'legend.scatterpoints')
  360. self.borderpad = mpl._val_or_rc(borderpad, 'legend.borderpad')
  361. self.labelspacing = mpl._val_or_rc(labelspacing, 'legend.labelspacing')
  362. self.handlelength = mpl._val_or_rc(handlelength, 'legend.handlelength')
  363. self.handleheight = mpl._val_or_rc(handleheight, 'legend.handleheight')
  364. self.handletextpad = mpl._val_or_rc(handletextpad, 'legend.handletextpad')
  365. self.borderaxespad = mpl._val_or_rc(borderaxespad, 'legend.borderaxespad')
  366. self.columnspacing = mpl._val_or_rc(columnspacing, 'legend.columnspacing')
  367. self.shadow = mpl._val_or_rc(shadow, 'legend.shadow')
  368. if reverse:
  369. labels = [*reversed(labels)]
  370. handles = [*reversed(handles)]
  371. handles = list(handles)
  372. if len(handles) < 2:
  373. ncols = 1
  374. self._ncols = ncols if ncols != 1 else ncol
  375. if self.numpoints <= 0:
  376. raise ValueError("numpoints must be > 0; it was %d" % numpoints)
  377. # introduce y-offset for handles of the scatter plot
  378. if scatteryoffsets is None:
  379. self._scatteryoffsets = np.array([3. / 8., 4. / 8., 2.5 / 8.])
  380. else:
  381. self._scatteryoffsets = np.asarray(scatteryoffsets)
  382. reps = self.scatterpoints // len(self._scatteryoffsets) + 1
  383. self._scatteryoffsets = np.tile(self._scatteryoffsets,
  384. reps)[:self.scatterpoints]
  385. # _legend_box is a VPacker instance that contains all
  386. # legend items and will be initialized from _init_legend_box()
  387. # method.
  388. self._legend_box = None
  389. if isinstance(parent, Axes):
  390. self.isaxes = True
  391. self.axes = parent
  392. self.set_figure(parent.get_figure(root=False))
  393. elif isinstance(parent, FigureBase):
  394. self.isaxes = False
  395. self.set_figure(parent)
  396. else:
  397. raise TypeError(
  398. "Legend needs either Axes or FigureBase as parent"
  399. )
  400. self.parent = parent
  401. self._mode = mode
  402. self.set_bbox_to_anchor(bbox_to_anchor, bbox_transform)
  403. # Figure out if self.shadow is valid
  404. # If shadow was None, rcParams loads False
  405. # So it shouldn't be None here
  406. self._shadow_props = {'ox': 2, 'oy': -2} # default location offsets
  407. if isinstance(self.shadow, dict):
  408. self._shadow_props.update(self.shadow)
  409. self.shadow = True
  410. elif self.shadow in (0, 1, True, False):
  411. self.shadow = bool(self.shadow)
  412. else:
  413. raise ValueError(
  414. 'Legend shadow must be a dict or bool, not '
  415. f'{self.shadow!r} of type {type(self.shadow)}.'
  416. )
  417. # We use FancyBboxPatch to draw a legend frame. The location
  418. # and size of the box will be updated during the drawing time.
  419. facecolor = mpl._val_or_rc(facecolor, "legend.facecolor")
  420. if facecolor == 'inherit':
  421. facecolor = mpl.rcParams["axes.facecolor"]
  422. edgecolor = mpl._val_or_rc(edgecolor, "legend.edgecolor")
  423. if edgecolor == 'inherit':
  424. edgecolor = mpl.rcParams["axes.edgecolor"]
  425. fancybox = mpl._val_or_rc(fancybox, "legend.fancybox")
  426. self.legendPatch = FancyBboxPatch(
  427. xy=(0, 0), width=1, height=1,
  428. facecolor=facecolor, edgecolor=edgecolor,
  429. # If shadow is used, default to alpha=1 (#8943).
  430. alpha=(framealpha if framealpha is not None
  431. else 1 if shadow
  432. else mpl.rcParams["legend.framealpha"]),
  433. # The width and height of the legendPatch will be set (in draw())
  434. # to the length that includes the padding. Thus we set pad=0 here.
  435. boxstyle=("round,pad=0,rounding_size=0.2" if fancybox
  436. else "square,pad=0"),
  437. mutation_scale=self._fontsize,
  438. snap=True,
  439. visible=mpl._val_or_rc(frameon, "legend.frameon")
  440. )
  441. self._set_artist_props(self.legendPatch)
  442. _api.check_in_list(["center", "left", "right"], alignment=alignment)
  443. self._alignment = alignment
  444. # init with null renderer
  445. self._init_legend_box(handles, labels, markerfirst)
  446. # Set legend location
  447. self.set_loc(loc)
  448. # figure out title font properties:
  449. if title_fontsize is not None and title_fontproperties is not None:
  450. raise ValueError(
  451. "title_fontsize and title_fontproperties can't be specified "
  452. "at the same time. Only use one of them. ")
  453. title_prop_fp = FontProperties._from_any(title_fontproperties)
  454. if isinstance(title_fontproperties, dict):
  455. if "size" not in title_fontproperties:
  456. title_fontsize = mpl.rcParams["legend.title_fontsize"]
  457. title_prop_fp.set_size(title_fontsize)
  458. elif title_fontsize is not None:
  459. title_prop_fp.set_size(title_fontsize)
  460. elif not isinstance(title_fontproperties, FontProperties):
  461. title_fontsize = mpl.rcParams["legend.title_fontsize"]
  462. title_prop_fp.set_size(title_fontsize)
  463. self.set_title(title, prop=title_prop_fp)
  464. self._draggable = None
  465. self.set_draggable(state=draggable)
  466. # set the text color
  467. color_getters = { # getter function depends on line or patch
  468. 'linecolor': ['get_color', 'get_facecolor'],
  469. 'markerfacecolor': ['get_markerfacecolor', 'get_facecolor'],
  470. 'mfc': ['get_markerfacecolor', 'get_facecolor'],
  471. 'markeredgecolor': ['get_markeredgecolor', 'get_edgecolor'],
  472. 'mec': ['get_markeredgecolor', 'get_edgecolor'],
  473. }
  474. labelcolor = mpl._val_or_rc(labelcolor, 'legend.labelcolor')
  475. if labelcolor is None:
  476. labelcolor = mpl.rcParams['text.color']
  477. if isinstance(labelcolor, str) and labelcolor in color_getters:
  478. getter_names = color_getters[labelcolor]
  479. for handle, text in zip(self.legend_handles, self.texts):
  480. try:
  481. if handle.get_array() is not None:
  482. continue
  483. except AttributeError:
  484. pass
  485. for getter_name in getter_names:
  486. try:
  487. color = getattr(handle, getter_name)()
  488. if isinstance(color, np.ndarray):
  489. if (
  490. color.shape[0] == 1
  491. or np.isclose(color, color[0]).all()
  492. ):
  493. text.set_color(color[0])
  494. else:
  495. pass
  496. else:
  497. text.set_color(color)
  498. break
  499. except AttributeError:
  500. pass
  501. elif cbook._str_equal(labelcolor, 'none'):
  502. for text in self.texts:
  503. text.set_color(labelcolor)
  504. elif np.iterable(labelcolor):
  505. for text, color in zip(self.texts,
  506. itertools.cycle(
  507. colors.to_rgba_array(labelcolor))):
  508. text.set_color(color)
  509. else:
  510. raise ValueError(f"Invalid labelcolor: {labelcolor!r}")
  511. def _set_artist_props(self, a):
  512. """
  513. Set the boilerplate props for artists added to Axes.
  514. """
  515. a.set_figure(self.get_figure(root=False))
  516. if self.isaxes:
  517. a.axes = self.axes
  518. a.set_transform(self.get_transform())
  519. @_docstring.interpd
  520. def set_loc(self, loc=None):
  521. """
  522. Set the location of the legend.
  523. .. versionadded:: 3.8
  524. Parameters
  525. ----------
  526. %(_legend_kw_set_loc_doc)s
  527. """
  528. loc0 = loc
  529. self._loc_used_default = loc is None
  530. if loc is None:
  531. loc = mpl.rcParams["legend.loc"]
  532. if not self.isaxes and loc in [0, 'best']:
  533. loc = 'upper right'
  534. type_err_message = ("loc must be string, coordinate tuple, or"
  535. f" an integer 0-10, not {loc!r}")
  536. # handle outside legends:
  537. self._outside_loc = None
  538. if isinstance(loc, str):
  539. if loc.split()[0] == 'outside':
  540. # strip outside:
  541. loc = loc.split('outside ')[1]
  542. # strip "center" at the beginning
  543. self._outside_loc = loc.replace('center ', '')
  544. # strip first
  545. self._outside_loc = self._outside_loc.split()[0]
  546. locs = loc.split()
  547. if len(locs) > 1 and locs[0] in ('right', 'left'):
  548. # locs doesn't accept "left upper", etc, so swap
  549. if locs[0] != 'center':
  550. locs = locs[::-1]
  551. loc = locs[0] + ' ' + locs[1]
  552. # check that loc is in acceptable strings
  553. loc = _api.check_getitem(self.codes, loc=loc)
  554. elif np.iterable(loc):
  555. # coerce iterable into tuple
  556. loc = tuple(loc)
  557. # validate the tuple represents Real coordinates
  558. if len(loc) != 2 or not all(isinstance(e, numbers.Real) for e in loc):
  559. raise ValueError(type_err_message)
  560. elif isinstance(loc, int):
  561. # validate the integer represents a string numeric value
  562. if loc < 0 or loc > 10:
  563. raise ValueError(type_err_message)
  564. else:
  565. # all other cases are invalid values of loc
  566. raise ValueError(type_err_message)
  567. if self.isaxes and self._outside_loc:
  568. raise ValueError(
  569. f"'outside' option for loc='{loc0}' keyword argument only "
  570. "works for figure legends")
  571. if not self.isaxes and loc == 0:
  572. raise ValueError(
  573. "Automatic legend placement (loc='best') not implemented for "
  574. "figure legend")
  575. tmp = self._loc_used_default
  576. self._set_loc(loc)
  577. self._loc_used_default = tmp # ignore changes done by _set_loc
  578. def _set_loc(self, loc):
  579. # find_offset function will be provided to _legend_box and
  580. # _legend_box will draw itself at the location of the return
  581. # value of the find_offset.
  582. self._loc_used_default = False
  583. self._loc_real = loc
  584. self.stale = True
  585. self._legend_box.set_offset(self._findoffset)
  586. def set_ncols(self, ncols):
  587. """Set the number of columns."""
  588. self._ncols = ncols
  589. def _get_loc(self):
  590. return self._loc_real
  591. _loc = property(_get_loc, _set_loc)
  592. def _findoffset(self, width, height, xdescent, ydescent, renderer):
  593. """Helper function to locate the legend."""
  594. if self._loc == 0: # "best".
  595. x, y = self._find_best_position(width, height, renderer)
  596. elif self._loc in Legend.codes.values(): # Fixed location.
  597. bbox = Bbox.from_bounds(0, 0, width, height)
  598. x, y = self._get_anchored_bbox(self._loc, bbox,
  599. self.get_bbox_to_anchor(),
  600. renderer)
  601. else: # Axes or figure coordinates.
  602. fx, fy = self._loc
  603. bbox = self.get_bbox_to_anchor()
  604. x, y = bbox.x0 + bbox.width * fx, bbox.y0 + bbox.height * fy
  605. return x + xdescent, y + ydescent
  606. @allow_rasterization
  607. def draw(self, renderer):
  608. # docstring inherited
  609. if not self.get_visible():
  610. return
  611. renderer.open_group('legend', gid=self.get_gid())
  612. fontsize = renderer.points_to_pixels(self._fontsize)
  613. # if mode == fill, set the width of the legend_box to the
  614. # width of the parent (minus pads)
  615. if self._mode in ["expand"]:
  616. pad = 2 * (self.borderaxespad + self.borderpad) * fontsize
  617. self._legend_box.set_width(self.get_bbox_to_anchor().width - pad)
  618. # update the location and size of the legend. This needs to
  619. # be done in any case to clip the figure right.
  620. bbox = self._legend_box.get_window_extent(renderer)
  621. self.legendPatch.set_bounds(bbox.bounds)
  622. self.legendPatch.set_mutation_scale(fontsize)
  623. # self.shadow is validated in __init__
  624. # So by here it is a bool and self._shadow_props contains any configs
  625. if self.shadow:
  626. Shadow(self.legendPatch, **self._shadow_props).draw(renderer)
  627. self.legendPatch.draw(renderer)
  628. self._legend_box.draw(renderer)
  629. renderer.close_group('legend')
  630. self.stale = False
  631. # _default_handler_map defines the default mapping between plot
  632. # elements and the legend handlers.
  633. _default_handler_map = {
  634. StemContainer: legend_handler.HandlerStem(),
  635. ErrorbarContainer: legend_handler.HandlerErrorbar(),
  636. Line2D: legend_handler.HandlerLine2D(),
  637. Patch: legend_handler.HandlerPatch(),
  638. StepPatch: legend_handler.HandlerStepPatch(),
  639. LineCollection: legend_handler.HandlerLineCollection(),
  640. RegularPolyCollection: legend_handler.HandlerRegularPolyCollection(),
  641. CircleCollection: legend_handler.HandlerCircleCollection(),
  642. BarContainer: legend_handler.HandlerPatch(
  643. update_func=legend_handler.update_from_first_child),
  644. tuple: legend_handler.HandlerTuple(),
  645. PathCollection: legend_handler.HandlerPathCollection(),
  646. PolyCollection: legend_handler.HandlerPolyCollection()
  647. }
  648. # (get|set|update)_default_handler_maps are public interfaces to
  649. # modify the default handler map.
  650. @classmethod
  651. def get_default_handler_map(cls):
  652. """Return the global default handler map, shared by all legends."""
  653. return cls._default_handler_map
  654. @classmethod
  655. def set_default_handler_map(cls, handler_map):
  656. """Set the global default handler map, shared by all legends."""
  657. cls._default_handler_map = handler_map
  658. @classmethod
  659. def update_default_handler_map(cls, handler_map):
  660. """Update the global default handler map, shared by all legends."""
  661. cls._default_handler_map.update(handler_map)
  662. def get_legend_handler_map(self):
  663. """Return this legend instance's handler map."""
  664. default_handler_map = self.get_default_handler_map()
  665. return ({**default_handler_map, **self._custom_handler_map}
  666. if self._custom_handler_map else default_handler_map)
  667. @staticmethod
  668. def get_legend_handler(legend_handler_map, orig_handle):
  669. """
  670. Return a legend handler from *legend_handler_map* that
  671. corresponds to *orig_handler*.
  672. *legend_handler_map* should be a dictionary object (that is
  673. returned by the get_legend_handler_map method).
  674. It first checks if the *orig_handle* itself is a key in the
  675. *legend_handler_map* and return the associated value.
  676. Otherwise, it checks for each of the classes in its
  677. method-resolution-order. If no matching key is found, it
  678. returns ``None``.
  679. """
  680. try:
  681. return legend_handler_map[orig_handle]
  682. except (TypeError, KeyError): # TypeError if unhashable.
  683. pass
  684. for handle_type in type(orig_handle).mro():
  685. try:
  686. return legend_handler_map[handle_type]
  687. except KeyError:
  688. pass
  689. return None
  690. def _init_legend_box(self, handles, labels, markerfirst=True):
  691. """
  692. Initialize the legend_box. The legend_box is an instance of
  693. the OffsetBox, which is packed with legend handles and
  694. texts. Once packed, their location is calculated during the
  695. drawing time.
  696. """
  697. fontsize = self._fontsize
  698. # legend_box is a HPacker, horizontally packed with columns.
  699. # Each column is a VPacker, vertically packed with legend items.
  700. # Each legend item is a HPacker packed with:
  701. # - handlebox: a DrawingArea which contains the legend handle.
  702. # - labelbox: a TextArea which contains the legend text.
  703. text_list = [] # the list of text instances
  704. handle_list = [] # the list of handle instances
  705. handles_and_labels = []
  706. # The approximate height and descent of text. These values are
  707. # only used for plotting the legend handle.
  708. descent = 0.35 * fontsize * (self.handleheight - 0.7) # heuristic.
  709. height = fontsize * self.handleheight - descent
  710. # each handle needs to be drawn inside a box of (x, y, w, h) =
  711. # (0, -descent, width, height). And their coordinates should
  712. # be given in the display coordinates.
  713. # The transformation of each handle will be automatically set
  714. # to self.get_transform(). If the artist does not use its
  715. # default transform (e.g., Collections), you need to
  716. # manually set their transform to the self.get_transform().
  717. legend_handler_map = self.get_legend_handler_map()
  718. for orig_handle, label in zip(handles, labels):
  719. handler = self.get_legend_handler(legend_handler_map, orig_handle)
  720. if handler is None:
  721. _api.warn_external(
  722. "Legend does not support handles for "
  723. f"{type(orig_handle).__name__} "
  724. "instances.\nA proxy artist may be used "
  725. "instead.\nSee: https://matplotlib.org/"
  726. "stable/users/explain/axes/legend_guide.html"
  727. "#controlling-the-legend-entries")
  728. # No handle for this artist, so we just defer to None.
  729. handle_list.append(None)
  730. else:
  731. textbox = TextArea(label, multilinebaseline=True,
  732. textprops=dict(
  733. verticalalignment='baseline',
  734. horizontalalignment='left',
  735. fontproperties=self.prop))
  736. handlebox = DrawingArea(width=self.handlelength * fontsize,
  737. height=height,
  738. xdescent=0., ydescent=descent)
  739. text_list.append(textbox._text)
  740. # Create the artist for the legend which represents the
  741. # original artist/handle.
  742. handle_list.append(handler.legend_artist(self, orig_handle,
  743. fontsize, handlebox))
  744. handles_and_labels.append((handlebox, textbox))
  745. columnbox = []
  746. # array_split splits n handles_and_labels into ncols columns, with the
  747. # first n%ncols columns having an extra entry. filter(len, ...)
  748. # handles the case where n < ncols: the last ncols-n columns are empty
  749. # and get filtered out.
  750. for handles_and_labels_column in filter(
  751. len, np.array_split(handles_and_labels, self._ncols)):
  752. # pack handlebox and labelbox into itembox
  753. itemboxes = [HPacker(pad=0,
  754. sep=self.handletextpad * fontsize,
  755. children=[h, t] if markerfirst else [t, h],
  756. align="baseline")
  757. for h, t in handles_and_labels_column]
  758. # pack columnbox
  759. alignment = "baseline" if markerfirst else "right"
  760. columnbox.append(VPacker(pad=0,
  761. sep=self.labelspacing * fontsize,
  762. align=alignment,
  763. children=itemboxes))
  764. mode = "expand" if self._mode == "expand" else "fixed"
  765. sep = self.columnspacing * fontsize
  766. self._legend_handle_box = HPacker(pad=0,
  767. sep=sep, align="baseline",
  768. mode=mode,
  769. children=columnbox)
  770. self._legend_title_box = TextArea("")
  771. self._legend_box = VPacker(pad=self.borderpad * fontsize,
  772. sep=self.labelspacing * fontsize,
  773. align=self._alignment,
  774. children=[self._legend_title_box,
  775. self._legend_handle_box])
  776. self._legend_box.set_figure(self.get_figure(root=False))
  777. self._legend_box.axes = self.axes
  778. self.texts = text_list
  779. self.legend_handles = handle_list
  780. def _auto_legend_data(self, renderer):
  781. """
  782. Return display coordinates for hit testing for "best" positioning.
  783. Returns
  784. -------
  785. bboxes
  786. List of bounding boxes of all patches.
  787. lines
  788. List of `.Path` corresponding to each line.
  789. offsets
  790. List of (x, y) offsets of all collection.
  791. """
  792. assert self.isaxes # always holds, as this is only called internally
  793. bboxes = []
  794. lines = []
  795. offsets = []
  796. for artist in self.parent._children:
  797. if isinstance(artist, Line2D):
  798. lines.append(
  799. artist.get_transform().transform_path(artist.get_path()))
  800. elif isinstance(artist, Rectangle):
  801. bboxes.append(
  802. artist.get_bbox().transformed(artist.get_data_transform()))
  803. elif isinstance(artist, Patch):
  804. lines.append(
  805. artist.get_transform().transform_path(artist.get_path()))
  806. elif isinstance(artist, PolyCollection):
  807. lines.extend(artist.get_transform().transform_path(path)
  808. for path in artist.get_paths())
  809. elif isinstance(artist, Collection):
  810. transform, transOffset, hoffsets, _ = artist._prepare_points()
  811. if len(hoffsets):
  812. offsets.extend(transOffset.transform(hoffsets))
  813. elif isinstance(artist, Text):
  814. bboxes.append(artist.get_window_extent(renderer))
  815. return bboxes, lines, offsets
  816. def get_children(self):
  817. # docstring inherited
  818. return [self._legend_box, self.get_frame()]
  819. def get_frame(self):
  820. """Return the `~.patches.Rectangle` used to frame the legend."""
  821. return self.legendPatch
  822. def get_lines(self):
  823. r"""Return the list of `~.lines.Line2D`\s in the legend."""
  824. return [h for h in self.legend_handles if isinstance(h, Line2D)]
  825. def get_patches(self):
  826. r"""Return the list of `~.patches.Patch`\s in the legend."""
  827. return silent_list('Patch',
  828. [h for h in self.legend_handles
  829. if isinstance(h, Patch)])
  830. def get_texts(self):
  831. r"""Return the list of `~.text.Text`\s in the legend."""
  832. return silent_list('Text', self.texts)
  833. def set_alignment(self, alignment):
  834. """
  835. Set the alignment of the legend title and the box of entries.
  836. The entries are aligned as a single block, so that markers always
  837. lined up.
  838. Parameters
  839. ----------
  840. alignment : {'center', 'left', 'right'}.
  841. """
  842. _api.check_in_list(["center", "left", "right"], alignment=alignment)
  843. self._alignment = alignment
  844. self._legend_box.align = alignment
  845. def get_alignment(self):
  846. """Get the alignment value of the legend box"""
  847. return self._legend_box.align
  848. def set_title(self, title, prop=None):
  849. """
  850. Set legend title and title style.
  851. Parameters
  852. ----------
  853. title : str
  854. The legend title.
  855. prop : `.font_manager.FontProperties` or `str` or `pathlib.Path`
  856. The font properties of the legend title.
  857. If a `str`, it is interpreted as a fontconfig pattern parsed by
  858. `.FontProperties`. If a `pathlib.Path`, it is interpreted as the
  859. absolute path to a font file.
  860. """
  861. self._legend_title_box._text.set_text(title)
  862. if title:
  863. self._legend_title_box._text.set_visible(True)
  864. self._legend_title_box.set_visible(True)
  865. else:
  866. self._legend_title_box._text.set_visible(False)
  867. self._legend_title_box.set_visible(False)
  868. if prop is not None:
  869. self._legend_title_box._text.set_fontproperties(prop)
  870. self.stale = True
  871. def get_title(self):
  872. """Return the `.Text` instance for the legend title."""
  873. return self._legend_title_box._text
  874. def get_window_extent(self, renderer=None):
  875. # docstring inherited
  876. if renderer is None:
  877. renderer = self.get_figure(root=True)._get_renderer()
  878. return self._legend_box.get_window_extent(renderer=renderer)
  879. def get_tightbbox(self, renderer=None):
  880. # docstring inherited
  881. return self._legend_box.get_window_extent(renderer)
  882. def get_frame_on(self):
  883. """Get whether the legend box patch is drawn."""
  884. return self.legendPatch.get_visible()
  885. def set_frame_on(self, b):
  886. """
  887. Set whether the legend box patch is drawn.
  888. Parameters
  889. ----------
  890. b : bool
  891. """
  892. self.legendPatch.set_visible(b)
  893. self.stale = True
  894. draw_frame = set_frame_on # Backcompat alias.
  895. def get_bbox_to_anchor(self):
  896. """Return the bbox that the legend will be anchored to."""
  897. if self._bbox_to_anchor is None:
  898. return self.parent.bbox
  899. else:
  900. return self._bbox_to_anchor
  901. def set_bbox_to_anchor(self, bbox, transform=None):
  902. """
  903. Set the bbox that the legend will be anchored to.
  904. Parameters
  905. ----------
  906. bbox : `~matplotlib.transforms.BboxBase` or tuple
  907. The bounding box can be specified in the following ways:
  908. - A `.BboxBase` instance
  909. - A tuple of ``(left, bottom, width, height)`` in the given
  910. transform (normalized axes coordinate if None)
  911. - A tuple of ``(left, bottom)`` where the width and height will be
  912. assumed to be zero.
  913. - *None*, to remove the bbox anchoring, and use the parent bbox.
  914. transform : `~matplotlib.transforms.Transform`, optional
  915. A transform to apply to the bounding box. If not specified, this
  916. will use a transform to the bounding box of the parent.
  917. """
  918. if bbox is None:
  919. self._bbox_to_anchor = None
  920. return
  921. elif isinstance(bbox, BboxBase):
  922. self._bbox_to_anchor = bbox
  923. else:
  924. try:
  925. l = len(bbox)
  926. except TypeError as err:
  927. raise ValueError(f"Invalid bbox: {bbox}") from err
  928. if l == 2:
  929. bbox = [bbox[0], bbox[1], 0, 0]
  930. self._bbox_to_anchor = Bbox.from_bounds(*bbox)
  931. if transform is None:
  932. transform = BboxTransformTo(self.parent.bbox)
  933. self._bbox_to_anchor = TransformedBbox(self._bbox_to_anchor,
  934. transform)
  935. self.stale = True
  936. def _get_anchored_bbox(self, loc, bbox, parentbbox, renderer):
  937. """
  938. Place the *bbox* inside the *parentbbox* according to a given
  939. location code. Return the (x, y) coordinate of the bbox.
  940. Parameters
  941. ----------
  942. loc : int
  943. A location code in range(1, 11). This corresponds to the possible
  944. values for ``self._loc``, excluding "best".
  945. bbox : `~matplotlib.transforms.Bbox`
  946. bbox to be placed, in display coordinates.
  947. parentbbox : `~matplotlib.transforms.Bbox`
  948. A parent box which will contain the bbox, in display coordinates.
  949. """
  950. return offsetbox._get_anchored_bbox(
  951. loc, bbox, parentbbox,
  952. self.borderaxespad * renderer.points_to_pixels(self._fontsize))
  953. def _find_best_position(self, width, height, renderer):
  954. """Determine the best location to place the legend."""
  955. assert self.isaxes # always holds, as this is only called internally
  956. start_time = time.perf_counter()
  957. bboxes, lines, offsets = self._auto_legend_data(renderer)
  958. bbox = Bbox.from_bounds(0, 0, width, height)
  959. candidates = []
  960. for idx in range(1, len(self.codes)):
  961. l, b = self._get_anchored_bbox(idx, bbox,
  962. self.get_bbox_to_anchor(),
  963. renderer)
  964. legendBox = Bbox.from_bounds(l, b, width, height)
  965. # XXX TODO: If markers are present, it would be good to take them
  966. # into account when checking vertex overlaps in the next line.
  967. badness = (sum(legendBox.count_contains(line.vertices)
  968. for line in lines)
  969. + legendBox.count_contains(offsets)
  970. + legendBox.count_overlaps(bboxes)
  971. + sum(line.intersects_bbox(legendBox, filled=False)
  972. for line in lines))
  973. # Include the index to favor lower codes in case of a tie.
  974. candidates.append((badness, idx, (l, b)))
  975. if badness == 0:
  976. break
  977. _, _, (l, b) = min(candidates)
  978. if self._loc_used_default and time.perf_counter() - start_time > 1:
  979. _api.warn_external(
  980. 'Creating legend with loc="best" can be slow with large '
  981. 'amounts of data.')
  982. return l, b
  983. def contains(self, mouseevent):
  984. return self.legendPatch.contains(mouseevent)
  985. def set_draggable(self, state, use_blit=False, update='loc'):
  986. """
  987. Enable or disable mouse dragging support of the legend.
  988. Parameters
  989. ----------
  990. state : bool
  991. Whether mouse dragging is enabled.
  992. use_blit : bool, optional
  993. Use blitting for faster image composition. For details see
  994. :ref:`func-animation`.
  995. update : {'loc', 'bbox'}, optional
  996. The legend parameter to be changed when dragged:
  997. - 'loc': update the *loc* parameter of the legend
  998. - 'bbox': update the *bbox_to_anchor* parameter of the legend
  999. Returns
  1000. -------
  1001. `.DraggableLegend` or *None*
  1002. If *state* is ``True`` this returns the `.DraggableLegend` helper
  1003. instance. Otherwise this returns *None*.
  1004. """
  1005. if state:
  1006. if self._draggable is None:
  1007. self._draggable = DraggableLegend(self,
  1008. use_blit,
  1009. update=update)
  1010. else:
  1011. if self._draggable is not None:
  1012. self._draggable.disconnect()
  1013. self._draggable = None
  1014. return self._draggable
  1015. def get_draggable(self):
  1016. """Return ``True`` if the legend is draggable, ``False`` otherwise."""
  1017. return self._draggable is not None
  1018. # Helper functions to parse legend arguments for both `figure.legend` and
  1019. # `axes.legend`:
  1020. def _get_legend_handles(axs, legend_handler_map=None):
  1021. """Yield artists that can be used as handles in a legend."""
  1022. handles_original = []
  1023. for ax in axs:
  1024. handles_original += [
  1025. *(a for a in ax._children
  1026. if isinstance(a, (Line2D, Patch, Collection, Text))),
  1027. *ax.containers]
  1028. # support parasite Axes:
  1029. if hasattr(ax, 'parasites'):
  1030. for axx in ax.parasites:
  1031. handles_original += [
  1032. *(a for a in axx._children
  1033. if isinstance(a, (Line2D, Patch, Collection, Text))),
  1034. *axx.containers]
  1035. handler_map = {**Legend.get_default_handler_map(),
  1036. **(legend_handler_map or {})}
  1037. has_handler = Legend.get_legend_handler
  1038. for handle in handles_original:
  1039. label = handle.get_label()
  1040. if label != '_nolegend_' and has_handler(handler_map, handle):
  1041. yield handle
  1042. elif (label and not label.startswith('_') and
  1043. not has_handler(handler_map, handle)):
  1044. _api.warn_external(
  1045. "Legend does not support handles for "
  1046. f"{type(handle).__name__} "
  1047. "instances.\nSee: https://matplotlib.org/stable/"
  1048. "tutorials/intermediate/legend_guide.html"
  1049. "#implementing-a-custom-legend-handler")
  1050. continue
  1051. def _get_legend_handles_labels(axs, legend_handler_map=None):
  1052. """Return handles and labels for legend."""
  1053. handles = []
  1054. labels = []
  1055. for handle in _get_legend_handles(axs, legend_handler_map):
  1056. label = handle.get_label()
  1057. if label and not label.startswith('_'):
  1058. handles.append(handle)
  1059. labels.append(label)
  1060. return handles, labels
  1061. def _parse_legend_args(axs, *args, handles=None, labels=None, **kwargs):
  1062. """
  1063. Get the handles and labels from the calls to either ``figure.legend``
  1064. or ``axes.legend``.
  1065. The parser is a bit involved because we support::
  1066. legend()
  1067. legend(labels)
  1068. legend(handles, labels)
  1069. legend(labels=labels)
  1070. legend(handles=handles)
  1071. legend(handles=handles, labels=labels)
  1072. The behavior for a mixture of positional and keyword handles and labels
  1073. is undefined and issues a warning; it will be an error in the future.
  1074. Parameters
  1075. ----------
  1076. axs : list of `.Axes`
  1077. If handles are not given explicitly, the artists in these Axes are
  1078. used as handles.
  1079. *args : tuple
  1080. Positional parameters passed to ``legend()``.
  1081. handles
  1082. The value of the keyword argument ``legend(handles=...)``, or *None*
  1083. if that keyword argument was not used.
  1084. labels
  1085. The value of the keyword argument ``legend(labels=...)``, or *None*
  1086. if that keyword argument was not used.
  1087. **kwargs
  1088. All other keyword arguments passed to ``legend()``.
  1089. Returns
  1090. -------
  1091. handles : list of (`.Artist` or tuple of `.Artist`)
  1092. The legend handles.
  1093. labels : list of str
  1094. The legend labels.
  1095. kwargs : dict
  1096. *kwargs* with keywords handles and labels removed.
  1097. """
  1098. log = logging.getLogger(__name__)
  1099. handlers = kwargs.get('handler_map')
  1100. if (handles is not None or labels is not None) and args:
  1101. _api.warn_deprecated("3.9", message=(
  1102. "You have mixed positional and keyword arguments, some input may "
  1103. "be discarded. This is deprecated since %(since)s and will "
  1104. "become an error in %(removal)s."))
  1105. if (hasattr(handles, "__len__") and
  1106. hasattr(labels, "__len__") and
  1107. len(handles) != len(labels)):
  1108. _api.warn_external(f"Mismatched number of handles and labels: "
  1109. f"len(handles) = {len(handles)} "
  1110. f"len(labels) = {len(labels)}")
  1111. # if got both handles and labels as kwargs, make same length
  1112. if handles and labels:
  1113. handles, labels = zip(*zip(handles, labels))
  1114. elif handles is not None and labels is None:
  1115. labels = [handle.get_label() for handle in handles]
  1116. elif labels is not None and handles is None:
  1117. # Get as many handles as there are labels.
  1118. handles = [handle for handle, label
  1119. in zip(_get_legend_handles(axs, handlers), labels)]
  1120. elif len(args) == 0: # 0 args: automatically detect labels and handles.
  1121. handles, labels = _get_legend_handles_labels(axs, handlers)
  1122. if not handles:
  1123. _api.warn_external(
  1124. "No artists with labels found to put in legend. Note that "
  1125. "artists whose label start with an underscore are ignored "
  1126. "when legend() is called with no argument.")
  1127. elif len(args) == 1: # 1 arg: user defined labels, automatic handle detection.
  1128. labels, = args
  1129. if any(isinstance(l, Artist) for l in labels):
  1130. raise TypeError("A single argument passed to legend() must be a "
  1131. "list of labels, but found an Artist in there.")
  1132. # Get as many handles as there are labels.
  1133. handles = [handle for handle, label
  1134. in zip(_get_legend_handles(axs, handlers), labels)]
  1135. elif len(args) == 2: # 2 args: user defined handles and labels.
  1136. handles, labels = args[:2]
  1137. else:
  1138. raise _api.nargs_error('legend', '0-2', len(args))
  1139. return handles, labels, kwargs