offsetbox.py 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613
  1. r"""
  2. Container classes for `.Artist`\s.
  3. `OffsetBox`
  4. The base of all container artists defined in this module.
  5. `AnchoredOffsetbox`, `AnchoredText`
  6. Anchor and align an arbitrary `.Artist` or a text relative to the parent
  7. axes or a specific anchor point.
  8. `DrawingArea`
  9. A container with fixed width and height. Children have a fixed position
  10. inside the container and may be clipped.
  11. `HPacker`, `VPacker`
  12. Containers for layouting their children vertically or horizontally.
  13. `PaddedBox`
  14. A container to add a padding around an `.Artist`.
  15. `TextArea`
  16. Contains a single `.Text` instance.
  17. """
  18. import functools
  19. import numpy as np
  20. import matplotlib as mpl
  21. from matplotlib import _api, _docstring
  22. import matplotlib.artist as martist
  23. import matplotlib.path as mpath
  24. import matplotlib.text as mtext
  25. import matplotlib.transforms as mtransforms
  26. from matplotlib.font_manager import FontProperties
  27. from matplotlib.image import BboxImage
  28. from matplotlib.patches import (
  29. FancyBboxPatch, FancyArrowPatch, bbox_artist as mbbox_artist)
  30. from matplotlib.transforms import Bbox, BboxBase, TransformedBbox
  31. DEBUG = False
  32. def _compat_get_offset(meth):
  33. """
  34. Decorator for the get_offset method of OffsetBox and subclasses, that
  35. allows supporting both the new signature (self, bbox, renderer) and the old
  36. signature (self, width, height, xdescent, ydescent, renderer).
  37. """
  38. sigs = [lambda self, width, height, xdescent, ydescent, renderer: locals(),
  39. lambda self, bbox, renderer: locals()]
  40. @functools.wraps(meth)
  41. def get_offset(self, *args, **kwargs):
  42. params = _api.select_matching_signature(sigs, self, *args, **kwargs)
  43. bbox = (params["bbox"] if "bbox" in params else
  44. Bbox.from_bounds(-params["xdescent"], -params["ydescent"],
  45. params["width"], params["height"]))
  46. return meth(params["self"], bbox, params["renderer"])
  47. return get_offset
  48. # for debugging use
  49. def _bbox_artist(*args, **kwargs):
  50. if DEBUG:
  51. mbbox_artist(*args, **kwargs)
  52. def _get_packed_offsets(widths, total, sep, mode="fixed"):
  53. r"""
  54. Pack boxes specified by their *widths*.
  55. For simplicity of the description, the terminology used here assumes a
  56. horizontal layout, but the function works equally for a vertical layout.
  57. There are three packing *mode*\s:
  58. - 'fixed': The elements are packed tight to the left with a spacing of
  59. *sep* in between. If *total* is *None* the returned total will be the
  60. right edge of the last box. A non-*None* total will be passed unchecked
  61. to the output. In particular this means that right edge of the last
  62. box may be further to the right than the returned total.
  63. - 'expand': Distribute the boxes with equal spacing so that the left edge
  64. of the first box is at 0, and the right edge of the last box is at
  65. *total*. The parameter *sep* is ignored in this mode. A total of *None*
  66. is accepted and considered equal to 1. The total is returned unchanged
  67. (except for the conversion *None* to 1). If the total is smaller than
  68. the sum of the widths, the laid out boxes will overlap.
  69. - 'equal': If *total* is given, the total space is divided in N equal
  70. ranges and each box is left-aligned within its subspace.
  71. Otherwise (*total* is *None*), *sep* must be provided and each box is
  72. left-aligned in its subspace of width ``(max(widths) + sep)``. The
  73. total width is then calculated to be ``N * (max(widths) + sep)``.
  74. Parameters
  75. ----------
  76. widths : list of float
  77. Widths of boxes to be packed.
  78. total : float or None
  79. Intended total length. *None* if not used.
  80. sep : float or None
  81. Spacing between boxes.
  82. mode : {'fixed', 'expand', 'equal'}
  83. The packing mode.
  84. Returns
  85. -------
  86. total : float
  87. The total width needed to accommodate the laid out boxes.
  88. offsets : array of float
  89. The left offsets of the boxes.
  90. """
  91. _api.check_in_list(["fixed", "expand", "equal"], mode=mode)
  92. if mode == "fixed":
  93. offsets_ = np.cumsum([0] + [w + sep for w in widths])
  94. offsets = offsets_[:-1]
  95. if total is None:
  96. total = offsets_[-1] - sep
  97. return total, offsets
  98. elif mode == "expand":
  99. # This is a bit of a hack to avoid a TypeError when *total*
  100. # is None and used in conjugation with tight layout.
  101. if total is None:
  102. total = 1
  103. if len(widths) > 1:
  104. sep = (total - sum(widths)) / (len(widths) - 1)
  105. else:
  106. sep = 0
  107. offsets_ = np.cumsum([0] + [w + sep for w in widths])
  108. offsets = offsets_[:-1]
  109. return total, offsets
  110. elif mode == "equal":
  111. maxh = max(widths)
  112. if total is None:
  113. if sep is None:
  114. raise ValueError("total and sep cannot both be None when "
  115. "using layout mode 'equal'")
  116. total = (maxh + sep) * len(widths)
  117. else:
  118. sep = total / len(widths) - maxh
  119. offsets = (maxh + sep) * np.arange(len(widths))
  120. return total, offsets
  121. def _get_aligned_offsets(yspans, height, align="baseline"):
  122. """
  123. Align boxes each specified by their ``(y0, y1)`` spans.
  124. For simplicity of the description, the terminology used here assumes a
  125. horizontal layout (i.e., vertical alignment), but the function works
  126. equally for a vertical layout.
  127. Parameters
  128. ----------
  129. yspans
  130. List of (y0, y1) spans of boxes to be aligned.
  131. height : float or None
  132. Intended total height. If None, the maximum of the heights
  133. (``y1 - y0``) in *yspans* is used.
  134. align : {'baseline', 'left', 'top', 'right', 'bottom', 'center'}
  135. The alignment anchor of the boxes.
  136. Returns
  137. -------
  138. (y0, y1)
  139. y range spanned by the packing. If a *height* was originally passed
  140. in, then for all alignments other than "baseline", a span of ``(0,
  141. height)`` is used without checking that it is actually large enough).
  142. descent
  143. The descent of the packing.
  144. offsets
  145. The bottom offsets of the boxes.
  146. """
  147. _api.check_in_list(
  148. ["baseline", "left", "top", "right", "bottom", "center"], align=align)
  149. if height is None:
  150. height = max(y1 - y0 for y0, y1 in yspans)
  151. if align == "baseline":
  152. yspan = (min(y0 for y0, y1 in yspans), max(y1 for y0, y1 in yspans))
  153. offsets = [0] * len(yspans)
  154. elif align in ["left", "bottom"]:
  155. yspan = (0, height)
  156. offsets = [-y0 for y0, y1 in yspans]
  157. elif align in ["right", "top"]:
  158. yspan = (0, height)
  159. offsets = [height - y1 for y0, y1 in yspans]
  160. elif align == "center":
  161. yspan = (0, height)
  162. offsets = [(height - (y1 - y0)) * .5 - y0 for y0, y1 in yspans]
  163. return yspan, offsets
  164. class OffsetBox(martist.Artist):
  165. """
  166. A simple container artist.
  167. The child artists are meant to be drawn at a relative position to its
  168. parent.
  169. Being an artist itself, all parameters are passed on to `.Artist`.
  170. """
  171. def __init__(self, *args, **kwargs):
  172. super().__init__(*args)
  173. self._internal_update(kwargs)
  174. # Clipping has not been implemented in the OffsetBox family, so
  175. # disable the clip flag for consistency. It can always be turned back
  176. # on to zero effect.
  177. self.set_clip_on(False)
  178. self._children = []
  179. self._offset = (0, 0)
  180. def set_figure(self, fig):
  181. """
  182. Set the `.Figure` for the `.OffsetBox` and all its children.
  183. Parameters
  184. ----------
  185. fig : `~matplotlib.figure.Figure`
  186. """
  187. super().set_figure(fig)
  188. for c in self.get_children():
  189. c.set_figure(fig)
  190. @martist.Artist.axes.setter
  191. def axes(self, ax):
  192. # TODO deal with this better
  193. martist.Artist.axes.fset(self, ax)
  194. for c in self.get_children():
  195. if c is not None:
  196. c.axes = ax
  197. def contains(self, mouseevent):
  198. """
  199. Delegate the mouse event contains-check to the children.
  200. As a container, the `.OffsetBox` does not respond itself to
  201. mouseevents.
  202. Parameters
  203. ----------
  204. mouseevent : `~matplotlib.backend_bases.MouseEvent`
  205. Returns
  206. -------
  207. contains : bool
  208. Whether any values are within the radius.
  209. details : dict
  210. An artist-specific dictionary of details of the event context,
  211. such as which points are contained in the pick radius. See the
  212. individual Artist subclasses for details.
  213. See Also
  214. --------
  215. .Artist.contains
  216. """
  217. if self._different_canvas(mouseevent):
  218. return False, {}
  219. for c in self.get_children():
  220. a, b = c.contains(mouseevent)
  221. if a:
  222. return a, b
  223. return False, {}
  224. def set_offset(self, xy):
  225. """
  226. Set the offset.
  227. Parameters
  228. ----------
  229. xy : (float, float) or callable
  230. The (x, y) coordinates of the offset in display units. These can
  231. either be given explicitly as a tuple (x, y), or by providing a
  232. function that converts the extent into the offset. This function
  233. must have the signature::
  234. def offset(width, height, xdescent, ydescent, renderer) \
  235. -> (float, float)
  236. """
  237. self._offset = xy
  238. self.stale = True
  239. @_compat_get_offset
  240. def get_offset(self, bbox, renderer):
  241. """
  242. Return the offset as a tuple (x, y).
  243. The extent parameters have to be provided to handle the case where the
  244. offset is dynamically determined by a callable (see
  245. `~.OffsetBox.set_offset`).
  246. Parameters
  247. ----------
  248. bbox : `.Bbox`
  249. renderer : `.RendererBase` subclass
  250. """
  251. return (
  252. self._offset(bbox.width, bbox.height, -bbox.x0, -bbox.y0, renderer)
  253. if callable(self._offset)
  254. else self._offset)
  255. def set_width(self, width):
  256. """
  257. Set the width of the box.
  258. Parameters
  259. ----------
  260. width : float
  261. """
  262. self.width = width
  263. self.stale = True
  264. def set_height(self, height):
  265. """
  266. Set the height of the box.
  267. Parameters
  268. ----------
  269. height : float
  270. """
  271. self.height = height
  272. self.stale = True
  273. def get_visible_children(self):
  274. r"""Return a list of the visible child `.Artist`\s."""
  275. return [c for c in self._children if c.get_visible()]
  276. def get_children(self):
  277. r"""Return a list of the child `.Artist`\s."""
  278. return self._children
  279. def _get_bbox_and_child_offsets(self, renderer):
  280. """
  281. Return the bbox of the offsetbox and the child offsets.
  282. The bbox should satisfy ``x0 <= x1 and y0 <= y1``.
  283. Parameters
  284. ----------
  285. renderer : `.RendererBase` subclass
  286. Returns
  287. -------
  288. bbox
  289. list of (xoffset, yoffset) pairs
  290. """
  291. raise NotImplementedError(
  292. "get_bbox_and_offsets must be overridden in derived classes")
  293. def get_bbox(self, renderer):
  294. """Return the bbox of the offsetbox, ignoring parent offsets."""
  295. bbox, offsets = self._get_bbox_and_child_offsets(renderer)
  296. return bbox
  297. def get_window_extent(self, renderer=None):
  298. # docstring inherited
  299. if renderer is None:
  300. renderer = self.get_figure(root=True)._get_renderer()
  301. bbox = self.get_bbox(renderer)
  302. try: # Some subclasses redefine get_offset to take no args.
  303. px, py = self.get_offset(bbox, renderer)
  304. except TypeError:
  305. px, py = self.get_offset()
  306. return bbox.translated(px, py)
  307. def draw(self, renderer):
  308. """
  309. Update the location of children if necessary and draw them
  310. to the given *renderer*.
  311. """
  312. bbox, offsets = self._get_bbox_and_child_offsets(renderer)
  313. px, py = self.get_offset(bbox, renderer)
  314. for c, (ox, oy) in zip(self.get_visible_children(), offsets):
  315. c.set_offset((px + ox, py + oy))
  316. c.draw(renderer)
  317. _bbox_artist(self, renderer, fill=False, props=dict(pad=0.))
  318. self.stale = False
  319. class PackerBase(OffsetBox):
  320. def __init__(self, pad=0., sep=0., width=None, height=None,
  321. align="baseline", mode="fixed", children=None):
  322. """
  323. Parameters
  324. ----------
  325. pad : float, default: 0.0
  326. The boundary padding in points.
  327. sep : float, default: 0.0
  328. The spacing between items in points.
  329. width, height : float, optional
  330. Width and height of the container box in pixels, calculated if
  331. *None*.
  332. align : {'top', 'bottom', 'left', 'right', 'center', 'baseline'}, \
  333. default: 'baseline'
  334. Alignment of boxes.
  335. mode : {'fixed', 'expand', 'equal'}, default: 'fixed'
  336. The packing mode.
  337. - 'fixed' packs the given `.Artist`\\s tight with *sep* spacing.
  338. - 'expand' uses the maximal available space to distribute the
  339. artists with equal spacing in between.
  340. - 'equal': Each artist an equal fraction of the available space
  341. and is left-aligned (or top-aligned) therein.
  342. children : list of `.Artist`
  343. The artists to pack.
  344. Notes
  345. -----
  346. *pad* and *sep* are in points and will be scaled with the renderer
  347. dpi, while *width* and *height* are in pixels.
  348. """
  349. super().__init__()
  350. self.height = height
  351. self.width = width
  352. self.sep = sep
  353. self.pad = pad
  354. self.mode = mode
  355. self.align = align
  356. self._children = children
  357. class VPacker(PackerBase):
  358. """
  359. VPacker packs its children vertically, automatically adjusting their
  360. relative positions at draw time.
  361. .. code-block:: none
  362. +---------+
  363. | Child 1 |
  364. | Child 2 |
  365. | Child 3 |
  366. +---------+
  367. """
  368. def _get_bbox_and_child_offsets(self, renderer):
  369. # docstring inherited
  370. dpicor = renderer.points_to_pixels(1.)
  371. pad = self.pad * dpicor
  372. sep = self.sep * dpicor
  373. if self.width is not None:
  374. for c in self.get_visible_children():
  375. if isinstance(c, PackerBase) and c.mode == "expand":
  376. c.set_width(self.width)
  377. bboxes = [c.get_bbox(renderer) for c in self.get_visible_children()]
  378. (x0, x1), xoffsets = _get_aligned_offsets(
  379. [bbox.intervalx for bbox in bboxes], self.width, self.align)
  380. height, yoffsets = _get_packed_offsets(
  381. [bbox.height for bbox in bboxes], self.height, sep, self.mode)
  382. yoffsets = height - (yoffsets + [bbox.y1 for bbox in bboxes])
  383. ydescent = yoffsets[0]
  384. yoffsets = yoffsets - ydescent
  385. return (
  386. Bbox.from_bounds(x0, -ydescent, x1 - x0, height).padded(pad),
  387. [*zip(xoffsets, yoffsets)])
  388. class HPacker(PackerBase):
  389. """
  390. HPacker packs its children horizontally, automatically adjusting their
  391. relative positions at draw time.
  392. .. code-block:: none
  393. +-------------------------------+
  394. | Child 1 Child 2 Child 3 |
  395. +-------------------------------+
  396. """
  397. def _get_bbox_and_child_offsets(self, renderer):
  398. # docstring inherited
  399. dpicor = renderer.points_to_pixels(1.)
  400. pad = self.pad * dpicor
  401. sep = self.sep * dpicor
  402. bboxes = [c.get_bbox(renderer) for c in self.get_visible_children()]
  403. if not bboxes:
  404. return Bbox.from_bounds(0, 0, 0, 0).padded(pad), []
  405. (y0, y1), yoffsets = _get_aligned_offsets(
  406. [bbox.intervaly for bbox in bboxes], self.height, self.align)
  407. width, xoffsets = _get_packed_offsets(
  408. [bbox.width for bbox in bboxes], self.width, sep, self.mode)
  409. x0 = bboxes[0].x0
  410. xoffsets -= ([bbox.x0 for bbox in bboxes] - x0)
  411. return (Bbox.from_bounds(x0, y0, width, y1 - y0).padded(pad),
  412. [*zip(xoffsets, yoffsets)])
  413. class PaddedBox(OffsetBox):
  414. """
  415. A container to add a padding around an `.Artist`.
  416. The `.PaddedBox` contains a `.FancyBboxPatch` that is used to visualize
  417. it when rendering.
  418. .. code-block:: none
  419. +----------------------------+
  420. | |
  421. | |
  422. | |
  423. | <--pad--> Artist |
  424. | ^ |
  425. | pad |
  426. | v |
  427. +----------------------------+
  428. Attributes
  429. ----------
  430. pad : float
  431. The padding in points.
  432. patch : `.FancyBboxPatch`
  433. When *draw_frame* is True, this `.FancyBboxPatch` is made visible and
  434. creates a border around the box.
  435. """
  436. def __init__(self, child, pad=0., *, draw_frame=False, patch_attrs=None):
  437. """
  438. Parameters
  439. ----------
  440. child : `~matplotlib.artist.Artist`
  441. The contained `.Artist`.
  442. pad : float, default: 0.0
  443. The padding in points. This will be scaled with the renderer dpi.
  444. In contrast, *width* and *height* are in *pixels* and thus not
  445. scaled.
  446. draw_frame : bool
  447. Whether to draw the contained `.FancyBboxPatch`.
  448. patch_attrs : dict or None
  449. Additional parameters passed to the contained `.FancyBboxPatch`.
  450. """
  451. super().__init__()
  452. self.pad = pad
  453. self._children = [child]
  454. self.patch = FancyBboxPatch(
  455. xy=(0.0, 0.0), width=1., height=1.,
  456. facecolor='w', edgecolor='k',
  457. mutation_scale=1, # self.prop.get_size_in_points(),
  458. snap=True,
  459. visible=draw_frame,
  460. boxstyle="square,pad=0",
  461. )
  462. if patch_attrs is not None:
  463. self.patch.update(patch_attrs)
  464. def _get_bbox_and_child_offsets(self, renderer):
  465. # docstring inherited.
  466. pad = self.pad * renderer.points_to_pixels(1.)
  467. return (self._children[0].get_bbox(renderer).padded(pad), [(0, 0)])
  468. def draw(self, renderer):
  469. # docstring inherited
  470. bbox, offsets = self._get_bbox_and_child_offsets(renderer)
  471. px, py = self.get_offset(bbox, renderer)
  472. for c, (ox, oy) in zip(self.get_visible_children(), offsets):
  473. c.set_offset((px + ox, py + oy))
  474. self.draw_frame(renderer)
  475. for c in self.get_visible_children():
  476. c.draw(renderer)
  477. self.stale = False
  478. def update_frame(self, bbox, fontsize=None):
  479. self.patch.set_bounds(bbox.bounds)
  480. if fontsize:
  481. self.patch.set_mutation_scale(fontsize)
  482. self.stale = True
  483. def draw_frame(self, renderer):
  484. # update the location and size of the legend
  485. self.update_frame(self.get_window_extent(renderer))
  486. self.patch.draw(renderer)
  487. class DrawingArea(OffsetBox):
  488. """
  489. The DrawingArea can contain any Artist as a child. The DrawingArea
  490. has a fixed width and height. The position of children relative to
  491. the parent is fixed. The children can be clipped at the
  492. boundaries of the parent.
  493. """
  494. def __init__(self, width, height, xdescent=0., ydescent=0., clip=False):
  495. """
  496. Parameters
  497. ----------
  498. width, height : float
  499. Width and height of the container box.
  500. xdescent, ydescent : float
  501. Descent of the box in x- and y-direction.
  502. clip : bool
  503. Whether to clip the children to the box.
  504. """
  505. super().__init__()
  506. self.width = width
  507. self.height = height
  508. self.xdescent = xdescent
  509. self.ydescent = ydescent
  510. self._clip_children = clip
  511. self.offset_transform = mtransforms.Affine2D()
  512. self.dpi_transform = mtransforms.Affine2D()
  513. @property
  514. def clip_children(self):
  515. """
  516. If the children of this DrawingArea should be clipped
  517. by DrawingArea bounding box.
  518. """
  519. return self._clip_children
  520. @clip_children.setter
  521. def clip_children(self, val):
  522. self._clip_children = bool(val)
  523. self.stale = True
  524. def get_transform(self):
  525. """
  526. Return the `~matplotlib.transforms.Transform` applied to the children.
  527. """
  528. return self.dpi_transform + self.offset_transform
  529. def set_transform(self, t):
  530. """
  531. set_transform is ignored.
  532. """
  533. def set_offset(self, xy):
  534. """
  535. Set the offset of the container.
  536. Parameters
  537. ----------
  538. xy : (float, float)
  539. The (x, y) coordinates of the offset in display units.
  540. """
  541. self._offset = xy
  542. self.offset_transform.clear()
  543. self.offset_transform.translate(xy[0], xy[1])
  544. self.stale = True
  545. def get_offset(self):
  546. """Return offset of the container."""
  547. return self._offset
  548. def get_bbox(self, renderer):
  549. # docstring inherited
  550. dpi_cor = renderer.points_to_pixels(1.)
  551. return Bbox.from_bounds(
  552. -self.xdescent * dpi_cor, -self.ydescent * dpi_cor,
  553. self.width * dpi_cor, self.height * dpi_cor)
  554. def add_artist(self, a):
  555. """Add an `.Artist` to the container box."""
  556. self._children.append(a)
  557. if not a.is_transform_set():
  558. a.set_transform(self.get_transform())
  559. if self.axes is not None:
  560. a.axes = self.axes
  561. fig = self.get_figure(root=False)
  562. if fig is not None:
  563. a.set_figure(fig)
  564. def draw(self, renderer):
  565. # docstring inherited
  566. dpi_cor = renderer.points_to_pixels(1.)
  567. self.dpi_transform.clear()
  568. self.dpi_transform.scale(dpi_cor)
  569. # At this point the DrawingArea has a transform
  570. # to the display space so the path created is
  571. # good for clipping children
  572. tpath = mtransforms.TransformedPath(
  573. mpath.Path([[0, 0], [0, self.height],
  574. [self.width, self.height],
  575. [self.width, 0]]),
  576. self.get_transform())
  577. for c in self._children:
  578. if self._clip_children and not (c.clipbox or c._clippath):
  579. c.set_clip_path(tpath)
  580. c.draw(renderer)
  581. _bbox_artist(self, renderer, fill=False, props=dict(pad=0.))
  582. self.stale = False
  583. class TextArea(OffsetBox):
  584. """
  585. The TextArea is a container artist for a single Text instance.
  586. The text is placed at (0, 0) with baseline+left alignment, by default. The
  587. width and height of the TextArea instance is the width and height of its
  588. child text.
  589. """
  590. def __init__(self, s,
  591. *,
  592. textprops=None,
  593. multilinebaseline=False,
  594. ):
  595. """
  596. Parameters
  597. ----------
  598. s : str
  599. The text to be displayed.
  600. textprops : dict, default: {}
  601. Dictionary of keyword parameters to be passed to the `.Text`
  602. instance in the TextArea.
  603. multilinebaseline : bool, default: False
  604. Whether the baseline for multiline text is adjusted so that it
  605. is (approximately) center-aligned with single-line text.
  606. """
  607. if textprops is None:
  608. textprops = {}
  609. self._text = mtext.Text(0, 0, s, **textprops)
  610. super().__init__()
  611. self._children = [self._text]
  612. self.offset_transform = mtransforms.Affine2D()
  613. self._baseline_transform = mtransforms.Affine2D()
  614. self._text.set_transform(self.offset_transform +
  615. self._baseline_transform)
  616. self._multilinebaseline = multilinebaseline
  617. def set_text(self, s):
  618. """Set the text of this area as a string."""
  619. self._text.set_text(s)
  620. self.stale = True
  621. def get_text(self):
  622. """Return the string representation of this area's text."""
  623. return self._text.get_text()
  624. def set_multilinebaseline(self, t):
  625. """
  626. Set multilinebaseline.
  627. If True, the baseline for multiline text is adjusted so that it is
  628. (approximately) center-aligned with single-line text. This is used
  629. e.g. by the legend implementation so that single-line labels are
  630. baseline-aligned, but multiline labels are "center"-aligned with them.
  631. """
  632. self._multilinebaseline = t
  633. self.stale = True
  634. def get_multilinebaseline(self):
  635. """
  636. Get multilinebaseline.
  637. """
  638. return self._multilinebaseline
  639. def set_transform(self, t):
  640. """
  641. set_transform is ignored.
  642. """
  643. def set_offset(self, xy):
  644. """
  645. Set the offset of the container.
  646. Parameters
  647. ----------
  648. xy : (float, float)
  649. The (x, y) coordinates of the offset in display units.
  650. """
  651. self._offset = xy
  652. self.offset_transform.clear()
  653. self.offset_transform.translate(xy[0], xy[1])
  654. self.stale = True
  655. def get_offset(self):
  656. """Return offset of the container."""
  657. return self._offset
  658. def get_bbox(self, renderer):
  659. _, h_, d_ = mtext._get_text_metrics_with_cache(
  660. renderer, "lp", self._text._fontproperties,
  661. ismath="TeX" if self._text.get_usetex() else False,
  662. dpi=self.get_figure(root=True).dpi)
  663. bbox, info, yd = self._text._get_layout(renderer)
  664. w, h = bbox.size
  665. self._baseline_transform.clear()
  666. if len(info) > 1 and self._multilinebaseline:
  667. yd_new = 0.5 * h - 0.5 * (h_ - d_)
  668. self._baseline_transform.translate(0, yd - yd_new)
  669. yd = yd_new
  670. else: # single line
  671. h_d = max(h_ - d_, h - yd)
  672. h = h_d + yd
  673. ha = self._text.get_horizontalalignment()
  674. x0 = {"left": 0, "center": -w / 2, "right": -w}[ha]
  675. return Bbox.from_bounds(x0, -yd, w, h)
  676. def draw(self, renderer):
  677. # docstring inherited
  678. self._text.draw(renderer)
  679. _bbox_artist(self, renderer, fill=False, props=dict(pad=0.))
  680. self.stale = False
  681. class AuxTransformBox(OffsetBox):
  682. """
  683. An OffsetBox with an auxiliary transform.
  684. All child artists are first transformed with *aux_transform*, then
  685. translated with an offset (the same for all children) so the bounding
  686. box of the children matches the drawn box. (In other words, adding an
  687. arbitrary translation to *aux_transform* has no effect as it will be
  688. cancelled out by the later offsetting.)
  689. `AuxTransformBox` is similar to `.DrawingArea`, except that the extent of
  690. the box is not predetermined but calculated from the window extent of its
  691. children, and the extent of the children will be calculated in the
  692. transformed coordinate.
  693. """
  694. def __init__(self, aux_transform):
  695. self.aux_transform = aux_transform
  696. super().__init__()
  697. self.offset_transform = mtransforms.Affine2D()
  698. # ref_offset_transform makes offset_transform always relative to the
  699. # lower-left corner of the bbox of its children.
  700. self.ref_offset_transform = mtransforms.Affine2D()
  701. def add_artist(self, a):
  702. """Add an `.Artist` to the container box."""
  703. self._children.append(a)
  704. a.set_transform(self.get_transform())
  705. self.stale = True
  706. def get_transform(self):
  707. """Return the `.Transform` applied to the children."""
  708. return (self.aux_transform
  709. + self.ref_offset_transform
  710. + self.offset_transform)
  711. def set_transform(self, t):
  712. """
  713. set_transform is ignored.
  714. """
  715. def set_offset(self, xy):
  716. """
  717. Set the offset of the container.
  718. Parameters
  719. ----------
  720. xy : (float, float)
  721. The (x, y) coordinates of the offset in display units.
  722. """
  723. self._offset = xy
  724. self.offset_transform.clear()
  725. self.offset_transform.translate(xy[0], xy[1])
  726. self.stale = True
  727. def get_offset(self):
  728. """Return offset of the container."""
  729. return self._offset
  730. def get_bbox(self, renderer):
  731. # clear the offset transforms
  732. _off = self.offset_transform.get_matrix() # to be restored later
  733. self.ref_offset_transform.clear()
  734. self.offset_transform.clear()
  735. # calculate the extent
  736. bboxes = [c.get_window_extent(renderer) for c in self._children]
  737. ub = Bbox.union(bboxes)
  738. # adjust ref_offset_transform
  739. self.ref_offset_transform.translate(-ub.x0, -ub.y0)
  740. # restore offset transform
  741. self.offset_transform.set_matrix(_off)
  742. return Bbox.from_bounds(0, 0, ub.width, ub.height)
  743. def draw(self, renderer):
  744. # docstring inherited
  745. for c in self._children:
  746. c.draw(renderer)
  747. _bbox_artist(self, renderer, fill=False, props=dict(pad=0.))
  748. self.stale = False
  749. class AnchoredOffsetbox(OffsetBox):
  750. """
  751. An OffsetBox placed according to location *loc*.
  752. AnchoredOffsetbox has a single child. When multiple children are needed,
  753. use an extra OffsetBox to enclose them. By default, the offset box is
  754. anchored against its parent Axes. You may explicitly specify the
  755. *bbox_to_anchor*.
  756. """
  757. zorder = 5 # zorder of the legend
  758. # Location codes
  759. codes = {'upper right': 1,
  760. 'upper left': 2,
  761. 'lower left': 3,
  762. 'lower right': 4,
  763. 'right': 5,
  764. 'center left': 6,
  765. 'center right': 7,
  766. 'lower center': 8,
  767. 'upper center': 9,
  768. 'center': 10,
  769. }
  770. def __init__(self, loc, *,
  771. pad=0.4, borderpad=0.5,
  772. child=None, prop=None, frameon=True,
  773. bbox_to_anchor=None,
  774. bbox_transform=None,
  775. **kwargs):
  776. """
  777. Parameters
  778. ----------
  779. loc : str
  780. The box location. Valid locations are
  781. 'upper left', 'upper center', 'upper right',
  782. 'center left', 'center', 'center right',
  783. 'lower left', 'lower center', 'lower right'.
  784. For backward compatibility, numeric values are accepted as well.
  785. See the parameter *loc* of `.Legend` for details.
  786. pad : float, default: 0.4
  787. Padding around the child as fraction of the fontsize.
  788. borderpad : float, default: 0.5
  789. Padding between the offsetbox frame and the *bbox_to_anchor*.
  790. child : `.OffsetBox`
  791. The box that will be anchored.
  792. prop : `.FontProperties`
  793. This is only used as a reference for paddings. If not given,
  794. :rc:`legend.fontsize` is used.
  795. frameon : bool
  796. Whether to draw a frame around the box.
  797. bbox_to_anchor : `.BboxBase`, 2-tuple, or 4-tuple of floats
  798. Box that is used to position the legend in conjunction with *loc*.
  799. bbox_transform : None or :class:`matplotlib.transforms.Transform`
  800. The transform for the bounding box (*bbox_to_anchor*).
  801. **kwargs
  802. All other parameters are passed on to `.OffsetBox`.
  803. Notes
  804. -----
  805. See `.Legend` for a detailed description of the anchoring mechanism.
  806. """
  807. super().__init__(**kwargs)
  808. self.set_bbox_to_anchor(bbox_to_anchor, bbox_transform)
  809. self.set_child(child)
  810. if isinstance(loc, str):
  811. loc = _api.check_getitem(self.codes, loc=loc)
  812. self.loc = loc
  813. self.borderpad = borderpad
  814. self.pad = pad
  815. if prop is None:
  816. self.prop = FontProperties(size=mpl.rcParams["legend.fontsize"])
  817. else:
  818. self.prop = FontProperties._from_any(prop)
  819. if isinstance(prop, dict) and "size" not in prop:
  820. self.prop.set_size(mpl.rcParams["legend.fontsize"])
  821. self.patch = FancyBboxPatch(
  822. xy=(0.0, 0.0), width=1., height=1.,
  823. facecolor='w', edgecolor='k',
  824. mutation_scale=self.prop.get_size_in_points(),
  825. snap=True,
  826. visible=frameon,
  827. boxstyle="square,pad=0",
  828. )
  829. def set_child(self, child):
  830. """Set the child to be anchored."""
  831. self._child = child
  832. if child is not None:
  833. child.axes = self.axes
  834. self.stale = True
  835. def get_child(self):
  836. """Return the child."""
  837. return self._child
  838. def get_children(self):
  839. """Return the list of children."""
  840. return [self._child]
  841. def get_bbox(self, renderer):
  842. # docstring inherited
  843. fontsize = renderer.points_to_pixels(self.prop.get_size_in_points())
  844. pad = self.pad * fontsize
  845. return self.get_child().get_bbox(renderer).padded(pad)
  846. def get_bbox_to_anchor(self):
  847. """Return the bbox that the box is anchored to."""
  848. if self._bbox_to_anchor is None:
  849. return self.axes.bbox
  850. else:
  851. transform = self._bbox_to_anchor_transform
  852. if transform is None:
  853. return self._bbox_to_anchor
  854. else:
  855. return TransformedBbox(self._bbox_to_anchor, transform)
  856. def set_bbox_to_anchor(self, bbox, transform=None):
  857. """
  858. Set the bbox that the box is anchored to.
  859. *bbox* can be a Bbox instance, a list of [left, bottom, width,
  860. height], or a list of [left, bottom] where the width and
  861. height will be assumed to be zero. The bbox will be
  862. transformed to display coordinate by the given transform.
  863. """
  864. if bbox is None or isinstance(bbox, BboxBase):
  865. self._bbox_to_anchor = bbox
  866. else:
  867. try:
  868. l = len(bbox)
  869. except TypeError as err:
  870. raise ValueError(f"Invalid bbox: {bbox}") from err
  871. if l == 2:
  872. bbox = [bbox[0], bbox[1], 0, 0]
  873. self._bbox_to_anchor = Bbox.from_bounds(*bbox)
  874. self._bbox_to_anchor_transform = transform
  875. self.stale = True
  876. @_compat_get_offset
  877. def get_offset(self, bbox, renderer):
  878. # docstring inherited
  879. pad = (self.borderpad
  880. * renderer.points_to_pixels(self.prop.get_size_in_points()))
  881. bbox_to_anchor = self.get_bbox_to_anchor()
  882. x0, y0 = _get_anchored_bbox(
  883. self.loc, Bbox.from_bounds(0, 0, bbox.width, bbox.height),
  884. bbox_to_anchor, pad)
  885. return x0 - bbox.x0, y0 - bbox.y0
  886. def update_frame(self, bbox, fontsize=None):
  887. self.patch.set_bounds(bbox.bounds)
  888. if fontsize:
  889. self.patch.set_mutation_scale(fontsize)
  890. def draw(self, renderer):
  891. # docstring inherited
  892. if not self.get_visible():
  893. return
  894. # update the location and size of the legend
  895. bbox = self.get_window_extent(renderer)
  896. fontsize = renderer.points_to_pixels(self.prop.get_size_in_points())
  897. self.update_frame(bbox, fontsize)
  898. self.patch.draw(renderer)
  899. px, py = self.get_offset(self.get_bbox(renderer), renderer)
  900. self.get_child().set_offset((px, py))
  901. self.get_child().draw(renderer)
  902. self.stale = False
  903. def _get_anchored_bbox(loc, bbox, parentbbox, borderpad):
  904. """
  905. Return the (x, y) position of the *bbox* anchored at the *parentbbox* with
  906. the *loc* code with the *borderpad*.
  907. """
  908. # This is only called internally and *loc* should already have been
  909. # validated. If 0 (None), we just let ``bbox.anchored`` raise.
  910. c = [None, "NE", "NW", "SW", "SE", "E", "W", "E", "S", "N", "C"][loc]
  911. container = parentbbox.padded(-borderpad)
  912. return bbox.anchored(c, container=container).p0
  913. class AnchoredText(AnchoredOffsetbox):
  914. """
  915. AnchoredOffsetbox with Text.
  916. """
  917. def __init__(self, s, loc, *, pad=0.4, borderpad=0.5, prop=None, **kwargs):
  918. """
  919. Parameters
  920. ----------
  921. s : str
  922. Text.
  923. loc : str
  924. Location code. See `AnchoredOffsetbox`.
  925. pad : float, default: 0.4
  926. Padding around the text as fraction of the fontsize.
  927. borderpad : float, default: 0.5
  928. Spacing between the offsetbox frame and the *bbox_to_anchor*.
  929. prop : dict, optional
  930. Dictionary of keyword parameters to be passed to the
  931. `~matplotlib.text.Text` instance contained inside AnchoredText.
  932. **kwargs
  933. All other parameters are passed to `AnchoredOffsetbox`.
  934. """
  935. if prop is None:
  936. prop = {}
  937. badkwargs = {'va', 'verticalalignment'}
  938. if badkwargs & set(prop):
  939. raise ValueError(
  940. 'Mixing verticalalignment with AnchoredText is not supported.')
  941. self.txt = TextArea(s, textprops=prop)
  942. fp = self.txt._text.get_fontproperties()
  943. super().__init__(
  944. loc, pad=pad, borderpad=borderpad, child=self.txt, prop=fp,
  945. **kwargs)
  946. class OffsetImage(OffsetBox):
  947. def __init__(self, arr, *,
  948. zoom=1,
  949. cmap=None,
  950. norm=None,
  951. interpolation=None,
  952. origin=None,
  953. filternorm=True,
  954. filterrad=4.0,
  955. resample=False,
  956. dpi_cor=True,
  957. **kwargs
  958. ):
  959. super().__init__()
  960. self._dpi_cor = dpi_cor
  961. self.image = BboxImage(bbox=self.get_window_extent,
  962. cmap=cmap,
  963. norm=norm,
  964. interpolation=interpolation,
  965. origin=origin,
  966. filternorm=filternorm,
  967. filterrad=filterrad,
  968. resample=resample,
  969. **kwargs
  970. )
  971. self._children = [self.image]
  972. self.set_zoom(zoom)
  973. self.set_data(arr)
  974. def set_data(self, arr):
  975. self._data = np.asarray(arr)
  976. self.image.set_data(self._data)
  977. self.stale = True
  978. def get_data(self):
  979. return self._data
  980. def set_zoom(self, zoom):
  981. self._zoom = zoom
  982. self.stale = True
  983. def get_zoom(self):
  984. return self._zoom
  985. def get_offset(self):
  986. """Return offset of the container."""
  987. return self._offset
  988. def get_children(self):
  989. return [self.image]
  990. def get_bbox(self, renderer):
  991. dpi_cor = renderer.points_to_pixels(1.) if self._dpi_cor else 1.
  992. zoom = self.get_zoom()
  993. data = self.get_data()
  994. ny, nx = data.shape[:2]
  995. w, h = dpi_cor * nx * zoom, dpi_cor * ny * zoom
  996. return Bbox.from_bounds(0, 0, w, h)
  997. def draw(self, renderer):
  998. # docstring inherited
  999. self.image.draw(renderer)
  1000. # bbox_artist(self, renderer, fill=False, props=dict(pad=0.))
  1001. self.stale = False
  1002. class AnnotationBbox(martist.Artist, mtext._AnnotationBase):
  1003. """
  1004. Container for an `OffsetBox` referring to a specific position *xy*.
  1005. Optionally an arrow pointing from the offsetbox to *xy* can be drawn.
  1006. This is like `.Annotation`, but with `OffsetBox` instead of `.Text`.
  1007. """
  1008. zorder = 3
  1009. def __str__(self):
  1010. return f"AnnotationBbox({self.xy[0]:g},{self.xy[1]:g})"
  1011. @_docstring.interpd
  1012. def __init__(self, offsetbox, xy, xybox=None, xycoords='data', boxcoords=None, *,
  1013. frameon=True, pad=0.4, # FancyBboxPatch boxstyle.
  1014. annotation_clip=None,
  1015. box_alignment=(0.5, 0.5),
  1016. bboxprops=None,
  1017. arrowprops=None,
  1018. fontsize=None,
  1019. **kwargs):
  1020. """
  1021. Parameters
  1022. ----------
  1023. offsetbox : `OffsetBox`
  1024. xy : (float, float)
  1025. The point *(x, y)* to annotate. The coordinate system is determined
  1026. by *xycoords*.
  1027. xybox : (float, float), default: *xy*
  1028. The position *(x, y)* to place the text at. The coordinate system
  1029. is determined by *boxcoords*.
  1030. xycoords : single or two-tuple of str or `.Artist` or `.Transform` or \
  1031. callable, default: 'data'
  1032. The coordinate system that *xy* is given in. See the parameter
  1033. *xycoords* in `.Annotation` for a detailed description.
  1034. boxcoords : single or two-tuple of str or `.Artist` or `.Transform` \
  1035. or callable, default: value of *xycoords*
  1036. The coordinate system that *xybox* is given in. See the parameter
  1037. *textcoords* in `.Annotation` for a detailed description.
  1038. frameon : bool, default: True
  1039. By default, the text is surrounded by a white `.FancyBboxPatch`
  1040. (accessible as the ``patch`` attribute of the `.AnnotationBbox`).
  1041. If *frameon* is set to False, this patch is made invisible.
  1042. annotation_clip: bool or None, default: None
  1043. Whether to clip (i.e. not draw) the annotation when the annotation
  1044. point *xy* is outside the Axes area.
  1045. - If *True*, the annotation will be clipped when *xy* is outside
  1046. the Axes.
  1047. - If *False*, the annotation will always be drawn.
  1048. - If *None*, the annotation will be clipped when *xy* is outside
  1049. the Axes and *xycoords* is 'data'.
  1050. pad : float, default: 0.4
  1051. Padding around the offsetbox.
  1052. box_alignment : (float, float)
  1053. A tuple of two floats for a vertical and horizontal alignment of
  1054. the offset box w.r.t. the *boxcoords*.
  1055. The lower-left corner is (0, 0) and upper-right corner is (1, 1).
  1056. bboxprops : dict, optional
  1057. A dictionary of properties to set for the annotation bounding box,
  1058. for example *boxstyle* and *alpha*. See `.FancyBboxPatch` for
  1059. details.
  1060. arrowprops: dict, optional
  1061. Arrow properties, see `.Annotation` for description.
  1062. fontsize: float or str, optional
  1063. Translated to points and passed as *mutation_scale* into
  1064. `.FancyBboxPatch` to scale attributes of the box style (e.g. pad
  1065. or rounding_size). The name is chosen in analogy to `.Text` where
  1066. *fontsize* defines the mutation scale as well. If not given,
  1067. :rc:`legend.fontsize` is used. See `.Text.set_fontsize` for valid
  1068. values.
  1069. **kwargs
  1070. Other `AnnotationBbox` properties. See `.AnnotationBbox.set` for
  1071. a list.
  1072. """
  1073. martist.Artist.__init__(self)
  1074. mtext._AnnotationBase.__init__(
  1075. self, xy, xycoords=xycoords, annotation_clip=annotation_clip)
  1076. self.offsetbox = offsetbox
  1077. self.arrowprops = arrowprops.copy() if arrowprops is not None else None
  1078. self.set_fontsize(fontsize)
  1079. self.xybox = xybox if xybox is not None else xy
  1080. self.boxcoords = boxcoords if boxcoords is not None else xycoords
  1081. self._box_alignment = box_alignment
  1082. if arrowprops is not None:
  1083. self._arrow_relpos = self.arrowprops.pop("relpos", (0.5, 0.5))
  1084. self.arrow_patch = FancyArrowPatch((0, 0), (1, 1),
  1085. **self.arrowprops)
  1086. else:
  1087. self._arrow_relpos = None
  1088. self.arrow_patch = None
  1089. self.patch = FancyBboxPatch( # frame
  1090. xy=(0.0, 0.0), width=1., height=1.,
  1091. facecolor='w', edgecolor='k',
  1092. mutation_scale=self.prop.get_size_in_points(),
  1093. snap=True,
  1094. visible=frameon,
  1095. )
  1096. self.patch.set_boxstyle("square", pad=pad)
  1097. if bboxprops:
  1098. self.patch.set(**bboxprops)
  1099. self._internal_update(kwargs)
  1100. @property
  1101. def xyann(self):
  1102. return self.xybox
  1103. @xyann.setter
  1104. def xyann(self, xyann):
  1105. self.xybox = xyann
  1106. self.stale = True
  1107. @property
  1108. def anncoords(self):
  1109. return self.boxcoords
  1110. @anncoords.setter
  1111. def anncoords(self, coords):
  1112. self.boxcoords = coords
  1113. self.stale = True
  1114. def contains(self, mouseevent):
  1115. if self._different_canvas(mouseevent):
  1116. return False, {}
  1117. if not self._check_xy(None):
  1118. return False, {}
  1119. return self.offsetbox.contains(mouseevent)
  1120. # self.arrow_patch is currently not checked as this can be a line - JJ
  1121. def get_children(self):
  1122. children = [self.offsetbox, self.patch]
  1123. if self.arrow_patch:
  1124. children.append(self.arrow_patch)
  1125. return children
  1126. def set_figure(self, fig):
  1127. if self.arrow_patch is not None:
  1128. self.arrow_patch.set_figure(fig)
  1129. self.offsetbox.set_figure(fig)
  1130. martist.Artist.set_figure(self, fig)
  1131. def set_fontsize(self, s=None):
  1132. """
  1133. Set the fontsize in points.
  1134. If *s* is not given, reset to :rc:`legend.fontsize`.
  1135. """
  1136. if s is None:
  1137. s = mpl.rcParams["legend.fontsize"]
  1138. self.prop = FontProperties(size=s)
  1139. self.stale = True
  1140. def get_fontsize(self):
  1141. """Return the fontsize in points."""
  1142. return self.prop.get_size_in_points()
  1143. def get_window_extent(self, renderer=None):
  1144. # docstring inherited
  1145. if renderer is None:
  1146. renderer = self.get_figure(root=True)._get_renderer()
  1147. self.update_positions(renderer)
  1148. return Bbox.union([child.get_window_extent(renderer)
  1149. for child in self.get_children()])
  1150. def get_tightbbox(self, renderer=None):
  1151. # docstring inherited
  1152. if renderer is None:
  1153. renderer = self.get_figure(root=True)._get_renderer()
  1154. self.update_positions(renderer)
  1155. return Bbox.union([child.get_tightbbox(renderer)
  1156. for child in self.get_children()])
  1157. def update_positions(self, renderer):
  1158. """Update pixel positions for the annotated point, the text, and the arrow."""
  1159. ox0, oy0 = self._get_xy(renderer, self.xybox, self.boxcoords)
  1160. bbox = self.offsetbox.get_bbox(renderer)
  1161. fw, fh = self._box_alignment
  1162. self.offsetbox.set_offset(
  1163. (ox0 - fw*bbox.width - bbox.x0, oy0 - fh*bbox.height - bbox.y0))
  1164. bbox = self.offsetbox.get_window_extent(renderer)
  1165. self.patch.set_bounds(bbox.bounds)
  1166. mutation_scale = renderer.points_to_pixels(self.get_fontsize())
  1167. self.patch.set_mutation_scale(mutation_scale)
  1168. if self.arrowprops:
  1169. # Use FancyArrowPatch if self.arrowprops has "arrowstyle" key.
  1170. # Adjust the starting point of the arrow relative to the textbox.
  1171. # TODO: Rotation needs to be accounted.
  1172. arrow_begin = bbox.p0 + bbox.size * self._arrow_relpos
  1173. arrow_end = self._get_position_xy(renderer)
  1174. # The arrow (from arrow_begin to arrow_end) will be first clipped
  1175. # by patchA and patchB, then shrunk by shrinkA and shrinkB (in
  1176. # points). If patch A is not set, self.bbox_patch is used.
  1177. self.arrow_patch.set_positions(arrow_begin, arrow_end)
  1178. if "mutation_scale" in self.arrowprops:
  1179. mutation_scale = renderer.points_to_pixels(
  1180. self.arrowprops["mutation_scale"])
  1181. # Else, use fontsize-based mutation_scale defined above.
  1182. self.arrow_patch.set_mutation_scale(mutation_scale)
  1183. patchA = self.arrowprops.get("patchA", self.patch)
  1184. self.arrow_patch.set_patchA(patchA)
  1185. def draw(self, renderer):
  1186. # docstring inherited
  1187. if not self.get_visible() or not self._check_xy(renderer):
  1188. return
  1189. renderer.open_group(self.__class__.__name__, gid=self.get_gid())
  1190. self.update_positions(renderer)
  1191. if self.arrow_patch is not None:
  1192. if (self.arrow_patch.get_figure(root=False) is None and
  1193. (fig := self.get_figure(root=False)) is not None):
  1194. self.arrow_patch.set_figure(fig)
  1195. self.arrow_patch.draw(renderer)
  1196. self.patch.draw(renderer)
  1197. self.offsetbox.draw(renderer)
  1198. renderer.close_group(self.__class__.__name__)
  1199. self.stale = False
  1200. class DraggableBase:
  1201. """
  1202. Helper base class for a draggable artist (legend, offsetbox).
  1203. Derived classes must override the following methods::
  1204. def save_offset(self):
  1205. '''
  1206. Called when the object is picked for dragging; should save the
  1207. reference position of the artist.
  1208. '''
  1209. def update_offset(self, dx, dy):
  1210. '''
  1211. Called during the dragging; (*dx*, *dy*) is the pixel offset from
  1212. the point where the mouse drag started.
  1213. '''
  1214. Optionally, you may override the following method::
  1215. def finalize_offset(self):
  1216. '''Called when the mouse is released.'''
  1217. In the current implementation of `.DraggableLegend` and
  1218. `DraggableAnnotation`, `update_offset` places the artists in display
  1219. coordinates, and `finalize_offset` recalculates their position in axes
  1220. coordinate and set a relevant attribute.
  1221. """
  1222. def __init__(self, ref_artist, use_blit=False):
  1223. self.ref_artist = ref_artist
  1224. if not ref_artist.pickable():
  1225. ref_artist.set_picker(self._picker)
  1226. self.got_artist = False
  1227. self._use_blit = use_blit and self.canvas.supports_blit
  1228. callbacks = self.canvas.callbacks
  1229. self._disconnectors = [
  1230. functools.partial(
  1231. callbacks.disconnect, callbacks._connect_picklable(name, func))
  1232. for name, func in [
  1233. ("pick_event", self.on_pick),
  1234. ("button_release_event", self.on_release),
  1235. ("motion_notify_event", self.on_motion),
  1236. ]
  1237. ]
  1238. @staticmethod
  1239. def _picker(artist, mouseevent):
  1240. # A custom picker to prevent dragging on mouse scroll events
  1241. if mouseevent.name == "scroll_event":
  1242. return False, {}
  1243. return artist.contains(mouseevent)
  1244. # A property, not an attribute, to maintain picklability.
  1245. canvas = property(lambda self: self.ref_artist.get_figure(root=True).canvas)
  1246. cids = property(lambda self: [
  1247. disconnect.args[0] for disconnect in self._disconnectors[:2]])
  1248. def on_motion(self, evt):
  1249. if self._check_still_parented() and self.got_artist:
  1250. dx = evt.x - self.mouse_x
  1251. dy = evt.y - self.mouse_y
  1252. self.update_offset(dx, dy)
  1253. if self._use_blit:
  1254. self.canvas.restore_region(self.background)
  1255. self.ref_artist.draw(
  1256. self.ref_artist.get_figure(root=True)._get_renderer())
  1257. self.canvas.blit()
  1258. else:
  1259. self.canvas.draw()
  1260. def on_pick(self, evt):
  1261. if self._check_still_parented():
  1262. if evt.artist == self.ref_artist:
  1263. self.mouse_x = evt.mouseevent.x
  1264. self.mouse_y = evt.mouseevent.y
  1265. self.save_offset()
  1266. self.got_artist = True
  1267. if self.got_artist and self._use_blit:
  1268. self.ref_artist.set_animated(True)
  1269. self.canvas.draw()
  1270. fig = self.ref_artist.get_figure(root=False)
  1271. self.background = self.canvas.copy_from_bbox(fig.bbox)
  1272. self.ref_artist.draw(fig._get_renderer())
  1273. self.canvas.blit()
  1274. def on_release(self, event):
  1275. if self._check_still_parented() and self.got_artist:
  1276. self.finalize_offset()
  1277. self.got_artist = False
  1278. if self._use_blit:
  1279. self.canvas.restore_region(self.background)
  1280. self.ref_artist.draw(self.ref_artist.figure._get_renderer())
  1281. self.canvas.blit()
  1282. self.ref_artist.set_animated(False)
  1283. def _check_still_parented(self):
  1284. if self.ref_artist.get_figure(root=False) is None:
  1285. self.disconnect()
  1286. return False
  1287. else:
  1288. return True
  1289. def disconnect(self):
  1290. """Disconnect the callbacks."""
  1291. for disconnector in self._disconnectors:
  1292. disconnector()
  1293. def save_offset(self):
  1294. pass
  1295. def update_offset(self, dx, dy):
  1296. pass
  1297. def finalize_offset(self):
  1298. pass
  1299. class DraggableOffsetBox(DraggableBase):
  1300. def __init__(self, ref_artist, offsetbox, use_blit=False):
  1301. super().__init__(ref_artist, use_blit=use_blit)
  1302. self.offsetbox = offsetbox
  1303. def save_offset(self):
  1304. offsetbox = self.offsetbox
  1305. renderer = offsetbox.get_figure(root=True)._get_renderer()
  1306. offset = offsetbox.get_offset(offsetbox.get_bbox(renderer), renderer)
  1307. self.offsetbox_x, self.offsetbox_y = offset
  1308. self.offsetbox.set_offset(offset)
  1309. def update_offset(self, dx, dy):
  1310. loc_in_canvas = self.offsetbox_x + dx, self.offsetbox_y + dy
  1311. self.offsetbox.set_offset(loc_in_canvas)
  1312. def get_loc_in_canvas(self):
  1313. offsetbox = self.offsetbox
  1314. renderer = offsetbox.get_figure(root=True)._get_renderer()
  1315. bbox = offsetbox.get_bbox(renderer)
  1316. ox, oy = offsetbox._offset
  1317. loc_in_canvas = (ox + bbox.x0, oy + bbox.y0)
  1318. return loc_in_canvas
  1319. class DraggableAnnotation(DraggableBase):
  1320. def __init__(self, annotation, use_blit=False):
  1321. super().__init__(annotation, use_blit=use_blit)
  1322. self.annotation = annotation
  1323. def save_offset(self):
  1324. ann = self.annotation
  1325. self.ox, self.oy = ann.get_transform().transform(ann.xyann)
  1326. def update_offset(self, dx, dy):
  1327. ann = self.annotation
  1328. ann.xyann = ann.get_transform().inverted().transform(
  1329. (self.ox + dx, self.oy + dy))