artist.py 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855
  1. from collections import namedtuple
  2. import contextlib
  3. from functools import cache, reduce, wraps
  4. import inspect
  5. from inspect import Signature, Parameter
  6. import logging
  7. from numbers import Number, Real
  8. import operator
  9. import re
  10. import warnings
  11. import numpy as np
  12. import matplotlib as mpl
  13. from . import _api, cbook
  14. from .path import Path
  15. from .transforms import (BboxBase, Bbox, IdentityTransform, Transform, TransformedBbox,
  16. TransformedPatchPath, TransformedPath)
  17. _log = logging.getLogger(__name__)
  18. def _prevent_rasterization(draw):
  19. # We assume that by default artists are not allowed to rasterize (unless
  20. # its draw method is explicitly decorated). If it is being drawn after a
  21. # rasterized artist and it has reached a raster_depth of 0, we stop
  22. # rasterization so that it does not affect the behavior of normal artist
  23. # (e.g., change in dpi).
  24. @wraps(draw)
  25. def draw_wrapper(artist, renderer, *args, **kwargs):
  26. if renderer._raster_depth == 0 and renderer._rasterizing:
  27. # Only stop when we are not in a rasterized parent
  28. # and something has been rasterized since last stop.
  29. renderer.stop_rasterizing()
  30. renderer._rasterizing = False
  31. return draw(artist, renderer, *args, **kwargs)
  32. draw_wrapper._supports_rasterization = False
  33. return draw_wrapper
  34. def allow_rasterization(draw):
  35. """
  36. Decorator for Artist.draw method. Provides routines
  37. that run before and after the draw call. The before and after functions
  38. are useful for changing artist-dependent renderer attributes or making
  39. other setup function calls, such as starting and flushing a mixed-mode
  40. renderer.
  41. """
  42. @wraps(draw)
  43. def draw_wrapper(artist, renderer):
  44. try:
  45. if artist.get_rasterized():
  46. if renderer._raster_depth == 0 and not renderer._rasterizing:
  47. renderer.start_rasterizing()
  48. renderer._rasterizing = True
  49. renderer._raster_depth += 1
  50. else:
  51. if renderer._raster_depth == 0 and renderer._rasterizing:
  52. # Only stop when we are not in a rasterized parent
  53. # and something has be rasterized since last stop
  54. renderer.stop_rasterizing()
  55. renderer._rasterizing = False
  56. if artist.get_agg_filter() is not None:
  57. renderer.start_filter()
  58. return draw(artist, renderer)
  59. finally:
  60. if artist.get_agg_filter() is not None:
  61. renderer.stop_filter(artist.get_agg_filter())
  62. if artist.get_rasterized():
  63. renderer._raster_depth -= 1
  64. if (renderer._rasterizing and (fig := artist.get_figure(root=True)) and
  65. fig.suppressComposite):
  66. # restart rasterizing to prevent merging
  67. renderer.stop_rasterizing()
  68. renderer.start_rasterizing()
  69. draw_wrapper._supports_rasterization = True
  70. return draw_wrapper
  71. def _finalize_rasterization(draw):
  72. """
  73. Decorator for Artist.draw method. Needed on the outermost artist, i.e.
  74. Figure, to finish up if the render is still in rasterized mode.
  75. """
  76. @wraps(draw)
  77. def draw_wrapper(artist, renderer, *args, **kwargs):
  78. result = draw(artist, renderer, *args, **kwargs)
  79. if renderer._rasterizing:
  80. renderer.stop_rasterizing()
  81. renderer._rasterizing = False
  82. return result
  83. return draw_wrapper
  84. def _stale_axes_callback(self, val):
  85. if self.axes:
  86. self.axes.stale = val
  87. _XYPair = namedtuple("_XYPair", "x y")
  88. class _Unset:
  89. def __repr__(self):
  90. return "<UNSET>"
  91. _UNSET = _Unset()
  92. class Artist:
  93. """
  94. Abstract base class for objects that render into a FigureCanvas.
  95. Typically, all visible elements in a figure are subclasses of Artist.
  96. """
  97. zorder = 0
  98. def __init_subclass__(cls):
  99. # Decorate draw() method so that all artists are able to stop
  100. # rastrization when necessary. If the artist's draw method is already
  101. # decorated (has a `_supports_rasterization` attribute), it won't be
  102. # decorated.
  103. if not hasattr(cls.draw, "_supports_rasterization"):
  104. cls.draw = _prevent_rasterization(cls.draw)
  105. # Inject custom set() methods into the subclass with signature and
  106. # docstring based on the subclasses' properties.
  107. if not hasattr(cls.set, '_autogenerated_signature'):
  108. # Don't overwrite cls.set if the subclass or one of its parents
  109. # has defined a set method set itself.
  110. # If there was no explicit definition, cls.set is inherited from
  111. # the hierarchy of auto-generated set methods, which hold the
  112. # flag _autogenerated_signature.
  113. return
  114. cls.set = lambda self, **kwargs: Artist.set(self, **kwargs)
  115. cls.set.__name__ = "set"
  116. cls.set.__qualname__ = f"{cls.__qualname__}.set"
  117. cls._update_set_signature_and_docstring()
  118. _PROPERTIES_EXCLUDED_FROM_SET = [
  119. 'navigate_mode', # not a user-facing function
  120. 'figure', # changing the figure is such a profound operation
  121. # that we don't want this in set()
  122. '3d_properties', # cannot be used as a keyword due to leading digit
  123. ]
  124. @classmethod
  125. def _update_set_signature_and_docstring(cls):
  126. """
  127. Update the signature of the set function to list all properties
  128. as keyword arguments.
  129. Property aliases are not listed in the signature for brevity, but
  130. are still accepted as keyword arguments.
  131. """
  132. cls.set.__signature__ = Signature(
  133. [Parameter("self", Parameter.POSITIONAL_OR_KEYWORD),
  134. *[Parameter(prop, Parameter.KEYWORD_ONLY, default=_UNSET)
  135. for prop in ArtistInspector(cls).get_setters()
  136. if prop not in Artist._PROPERTIES_EXCLUDED_FROM_SET]])
  137. cls.set._autogenerated_signature = True
  138. cls.set.__doc__ = (
  139. "Set multiple properties at once.\n\n"
  140. "Supported properties are\n\n"
  141. + kwdoc(cls))
  142. def __init__(self):
  143. self._stale = True
  144. self.stale_callback = None
  145. self._axes = None
  146. self._parent_figure = None
  147. self._transform = None
  148. self._transformSet = False
  149. self._visible = True
  150. self._animated = False
  151. self._alpha = None
  152. self.clipbox = None
  153. self._clippath = None
  154. self._clipon = True
  155. self._label = ''
  156. self._picker = None
  157. self._rasterized = False
  158. self._agg_filter = None
  159. # Normally, artist classes need to be queried for mouseover info if and
  160. # only if they override get_cursor_data.
  161. self._mouseover = type(self).get_cursor_data != Artist.get_cursor_data
  162. self._callbacks = cbook.CallbackRegistry(signals=["pchanged"])
  163. try:
  164. self.axes = None
  165. except AttributeError:
  166. # Handle self.axes as a read-only property, as in Figure.
  167. pass
  168. self._remove_method = None
  169. self._url = None
  170. self._gid = None
  171. self._snap = None
  172. self._sketch = mpl.rcParams['path.sketch']
  173. self._path_effects = mpl.rcParams['path.effects']
  174. self._sticky_edges = _XYPair([], [])
  175. self._in_layout = True
  176. def __getstate__(self):
  177. d = self.__dict__.copy()
  178. d['stale_callback'] = None
  179. return d
  180. def remove(self):
  181. """
  182. Remove the artist from the figure if possible.
  183. The effect will not be visible until the figure is redrawn, e.g.,
  184. with `.FigureCanvasBase.draw_idle`. Call `~.axes.Axes.relim` to
  185. update the Axes limits if desired.
  186. Note: `~.axes.Axes.relim` will not see collections even if the
  187. collection was added to the Axes with *autolim* = True.
  188. Note: there is no support for removing the artist's legend entry.
  189. """
  190. # There is no method to set the callback. Instead, the parent should
  191. # set the _remove_method attribute directly. This would be a
  192. # protected attribute if Python supported that sort of thing. The
  193. # callback has one parameter, which is the child to be removed.
  194. if self._remove_method is not None:
  195. self._remove_method(self)
  196. # clear stale callback
  197. self.stale_callback = None
  198. _ax_flag = False
  199. if hasattr(self, 'axes') and self.axes:
  200. # remove from the mouse hit list
  201. self.axes._mouseover_set.discard(self)
  202. self.axes.stale = True
  203. self.axes = None # decouple the artist from the Axes
  204. _ax_flag = True
  205. if (fig := self.get_figure(root=False)) is not None:
  206. if not _ax_flag:
  207. fig.stale = True
  208. self._parent_figure = None
  209. else:
  210. raise NotImplementedError('cannot remove artist')
  211. # TODO: the fix for the collections relim problem is to move the
  212. # limits calculation into the artist itself, including the property of
  213. # whether or not the artist should affect the limits. Then there will
  214. # be no distinction between axes.add_line, axes.add_patch, etc.
  215. # TODO: add legend support
  216. def have_units(self):
  217. """Return whether units are set on any axis."""
  218. ax = self.axes
  219. return ax and any(axis.have_units() for axis in ax._axis_map.values())
  220. def convert_xunits(self, x):
  221. """
  222. Convert *x* using the unit type of the xaxis.
  223. If the artist is not contained in an Axes or if the xaxis does not
  224. have units, *x* itself is returned.
  225. """
  226. ax = getattr(self, 'axes', None)
  227. if ax is None or ax.xaxis is None:
  228. return x
  229. return ax.xaxis.convert_units(x)
  230. def convert_yunits(self, y):
  231. """
  232. Convert *y* using the unit type of the yaxis.
  233. If the artist is not contained in an Axes or if the yaxis does not
  234. have units, *y* itself is returned.
  235. """
  236. ax = getattr(self, 'axes', None)
  237. if ax is None or ax.yaxis is None:
  238. return y
  239. return ax.yaxis.convert_units(y)
  240. @property
  241. def axes(self):
  242. """The `~.axes.Axes` instance the artist resides in, or *None*."""
  243. return self._axes
  244. @axes.setter
  245. def axes(self, new_axes):
  246. if (new_axes is not None and self._axes is not None
  247. and new_axes != self._axes):
  248. raise ValueError("Can not reset the Axes. You are probably trying to reuse "
  249. "an artist in more than one Axes which is not supported")
  250. self._axes = new_axes
  251. if new_axes is not None and new_axes is not self:
  252. self.stale_callback = _stale_axes_callback
  253. @property
  254. def stale(self):
  255. """
  256. Whether the artist is 'stale' and needs to be re-drawn for the output
  257. to match the internal state of the artist.
  258. """
  259. return self._stale
  260. @stale.setter
  261. def stale(self, val):
  262. self._stale = val
  263. # if the artist is animated it does not take normal part in the
  264. # draw stack and is not expected to be drawn as part of the normal
  265. # draw loop (when not saving) so do not propagate this change
  266. if self._animated:
  267. return
  268. if val and self.stale_callback is not None:
  269. self.stale_callback(self, val)
  270. def get_window_extent(self, renderer=None):
  271. """
  272. Get the artist's bounding box in display space.
  273. The bounding box' width and height are nonnegative.
  274. Subclasses should override for inclusion in the bounding box
  275. "tight" calculation. Default is to return an empty bounding
  276. box at 0, 0.
  277. Be careful when using this function, the results will not update
  278. if the artist window extent of the artist changes. The extent
  279. can change due to any changes in the transform stack, such as
  280. changing the Axes limits, the figure size, or the canvas used
  281. (as is done when saving a figure). This can lead to unexpected
  282. behavior where interactive figures will look fine on the screen,
  283. but will save incorrectly.
  284. """
  285. return Bbox([[0, 0], [0, 0]])
  286. def get_tightbbox(self, renderer=None):
  287. """
  288. Like `.Artist.get_window_extent`, but includes any clipping.
  289. Parameters
  290. ----------
  291. renderer : `~matplotlib.backend_bases.RendererBase` subclass, optional
  292. renderer that will be used to draw the figures (i.e.
  293. ``fig.canvas.get_renderer()``)
  294. Returns
  295. -------
  296. `.Bbox` or None
  297. The enclosing bounding box (in figure pixel coordinates).
  298. Returns None if clipping results in no intersection.
  299. """
  300. bbox = self.get_window_extent(renderer)
  301. if self.get_clip_on():
  302. clip_box = self.get_clip_box()
  303. if clip_box is not None:
  304. bbox = Bbox.intersection(bbox, clip_box)
  305. clip_path = self.get_clip_path()
  306. if clip_path is not None and bbox is not None:
  307. clip_path = clip_path.get_fully_transformed_path()
  308. bbox = Bbox.intersection(bbox, clip_path.get_extents())
  309. return bbox
  310. def add_callback(self, func):
  311. """
  312. Add a callback function that will be called whenever one of the
  313. `.Artist`'s properties changes.
  314. Parameters
  315. ----------
  316. func : callable
  317. The callback function. It must have the signature::
  318. def func(artist: Artist) -> Any
  319. where *artist* is the calling `.Artist`. Return values may exist
  320. but are ignored.
  321. Returns
  322. -------
  323. int
  324. The observer id associated with the callback. This id can be
  325. used for removing the callback with `.remove_callback` later.
  326. See Also
  327. --------
  328. remove_callback
  329. """
  330. # Wrapping func in a lambda ensures it can be connected multiple times
  331. # and never gets weakref-gc'ed.
  332. return self._callbacks.connect("pchanged", lambda: func(self))
  333. def remove_callback(self, oid):
  334. """
  335. Remove a callback based on its observer id.
  336. See Also
  337. --------
  338. add_callback
  339. """
  340. self._callbacks.disconnect(oid)
  341. def pchanged(self):
  342. """
  343. Call all of the registered callbacks.
  344. This function is triggered internally when a property is changed.
  345. See Also
  346. --------
  347. add_callback
  348. remove_callback
  349. """
  350. self._callbacks.process("pchanged")
  351. def is_transform_set(self):
  352. """
  353. Return whether the Artist has an explicitly set transform.
  354. This is *True* after `.set_transform` has been called.
  355. """
  356. return self._transformSet
  357. def set_transform(self, t):
  358. """
  359. Set the artist transform.
  360. Parameters
  361. ----------
  362. t : `~matplotlib.transforms.Transform`
  363. """
  364. self._transform = t
  365. self._transformSet = True
  366. self.pchanged()
  367. self.stale = True
  368. def get_transform(self):
  369. """Return the `.Transform` instance used by this artist."""
  370. if self._transform is None:
  371. self._transform = IdentityTransform()
  372. elif (not isinstance(self._transform, Transform)
  373. and hasattr(self._transform, '_as_mpl_transform')):
  374. self._transform = self._transform._as_mpl_transform(self.axes)
  375. return self._transform
  376. def get_children(self):
  377. r"""Return a list of the child `.Artist`\s of this `.Artist`."""
  378. return []
  379. def _different_canvas(self, event):
  380. """
  381. Check whether an *event* occurred on a canvas other that this artist's canvas.
  382. If this method returns True, the event definitely occurred on a different
  383. canvas; if it returns False, either it occurred on the same canvas, or we may
  384. not have enough information to know.
  385. Subclasses should start their definition of `contains` as follows::
  386. if self._different_canvas(mouseevent):
  387. return False, {}
  388. # subclass-specific implementation follows
  389. """
  390. return (getattr(event, "canvas", None) is not None
  391. and (fig := self.get_figure(root=True)) is not None
  392. and event.canvas is not fig.canvas)
  393. def contains(self, mouseevent):
  394. """
  395. Test whether the artist contains the mouse event.
  396. Parameters
  397. ----------
  398. mouseevent : `~matplotlib.backend_bases.MouseEvent`
  399. Returns
  400. -------
  401. contains : bool
  402. Whether any values are within the radius.
  403. details : dict
  404. An artist-specific dictionary of details of the event context,
  405. such as which points are contained in the pick radius. See the
  406. individual Artist subclasses for details.
  407. """
  408. _log.warning("%r needs 'contains' method", self.__class__.__name__)
  409. return False, {}
  410. def pickable(self):
  411. """
  412. Return whether the artist is pickable.
  413. See Also
  414. --------
  415. .Artist.set_picker, .Artist.get_picker, .Artist.pick
  416. """
  417. return self.get_figure(root=False) is not None and self._picker is not None
  418. def pick(self, mouseevent):
  419. """
  420. Process a pick event.
  421. Each child artist will fire a pick event if *mouseevent* is over
  422. the artist and the artist has picker set.
  423. See Also
  424. --------
  425. .Artist.set_picker, .Artist.get_picker, .Artist.pickable
  426. """
  427. from .backend_bases import PickEvent # Circular import.
  428. # Pick self
  429. if self.pickable():
  430. picker = self.get_picker()
  431. if callable(picker):
  432. inside, prop = picker(self, mouseevent)
  433. else:
  434. inside, prop = self.contains(mouseevent)
  435. if inside:
  436. PickEvent("pick_event", self.get_figure(root=True).canvas,
  437. mouseevent, self, **prop)._process()
  438. # Pick children
  439. for a in self.get_children():
  440. # make sure the event happened in the same Axes
  441. ax = getattr(a, 'axes', None)
  442. if (isinstance(a, mpl.figure.SubFigure)
  443. or mouseevent.inaxes is None or ax is None
  444. or mouseevent.inaxes == ax):
  445. # we need to check if mouseevent.inaxes is None
  446. # because some objects associated with an Axes (e.g., a
  447. # tick label) can be outside the bounding box of the
  448. # Axes and inaxes will be None
  449. # also check that ax is None so that it traverse objects
  450. # which do not have an axes property but children might
  451. a.pick(mouseevent)
  452. def set_picker(self, picker):
  453. """
  454. Define the picking behavior of the artist.
  455. Parameters
  456. ----------
  457. picker : None or bool or float or callable
  458. This can be one of the following:
  459. - *None*: Picking is disabled for this artist (default).
  460. - A boolean: If *True* then picking will be enabled and the
  461. artist will fire a pick event if the mouse event is over
  462. the artist.
  463. - A float: If picker is a number it is interpreted as an
  464. epsilon tolerance in points and the artist will fire
  465. off an event if its data is within epsilon of the mouse
  466. event. For some artists like lines and patch collections,
  467. the artist may provide additional data to the pick event
  468. that is generated, e.g., the indices of the data within
  469. epsilon of the pick event
  470. - A function: If picker is callable, it is a user supplied
  471. function which determines whether the artist is hit by the
  472. mouse event::
  473. hit, props = picker(artist, mouseevent)
  474. to determine the hit test. if the mouse event is over the
  475. artist, return *hit=True* and props is a dictionary of
  476. properties you want added to the PickEvent attributes.
  477. """
  478. self._picker = picker
  479. def get_picker(self):
  480. """
  481. Return the picking behavior of the artist.
  482. The possible values are described in `.Artist.set_picker`.
  483. See Also
  484. --------
  485. .Artist.set_picker, .Artist.pickable, .Artist.pick
  486. """
  487. return self._picker
  488. def get_url(self):
  489. """Return the url."""
  490. return self._url
  491. def set_url(self, url):
  492. """
  493. Set the url for the artist.
  494. Parameters
  495. ----------
  496. url : str
  497. """
  498. self._url = url
  499. def get_gid(self):
  500. """Return the group id."""
  501. return self._gid
  502. def set_gid(self, gid):
  503. """
  504. Set the (group) id for the artist.
  505. Parameters
  506. ----------
  507. gid : str
  508. """
  509. self._gid = gid
  510. def get_snap(self):
  511. """
  512. Return the snap setting.
  513. See `.set_snap` for details.
  514. """
  515. if mpl.rcParams['path.snap']:
  516. return self._snap
  517. else:
  518. return False
  519. def set_snap(self, snap):
  520. """
  521. Set the snapping behavior.
  522. Snapping aligns positions with the pixel grid, which results in
  523. clearer images. For example, if a black line of 1px width was
  524. defined at a position in between two pixels, the resulting image
  525. would contain the interpolated value of that line in the pixel grid,
  526. which would be a grey value on both adjacent pixel positions. In
  527. contrast, snapping will move the line to the nearest integer pixel
  528. value, so that the resulting image will really contain a 1px wide
  529. black line.
  530. Snapping is currently only supported by the Agg and MacOSX backends.
  531. Parameters
  532. ----------
  533. snap : bool or None
  534. Possible values:
  535. - *True*: Snap vertices to the nearest pixel center.
  536. - *False*: Do not modify vertex positions.
  537. - *None*: (auto) If the path contains only rectilinear line
  538. segments, round to the nearest pixel center.
  539. """
  540. self._snap = snap
  541. self.stale = True
  542. def get_sketch_params(self):
  543. """
  544. Return the sketch parameters for the artist.
  545. Returns
  546. -------
  547. tuple or None
  548. A 3-tuple with the following elements:
  549. - *scale*: The amplitude of the wiggle perpendicular to the
  550. source line.
  551. - *length*: The length of the wiggle along the line.
  552. - *randomness*: The scale factor by which the length is
  553. shrunken or expanded.
  554. Returns *None* if no sketch parameters were set.
  555. """
  556. return self._sketch
  557. def set_sketch_params(self, scale=None, length=None, randomness=None):
  558. """
  559. Set the sketch parameters.
  560. Parameters
  561. ----------
  562. scale : float, optional
  563. The amplitude of the wiggle perpendicular to the source
  564. line, in pixels. If scale is `None`, or not provided, no
  565. sketch filter will be provided.
  566. length : float, optional
  567. The length of the wiggle along the line, in pixels
  568. (default 128.0)
  569. randomness : float, optional
  570. The scale factor by which the length is shrunken or
  571. expanded (default 16.0)
  572. The PGF backend uses this argument as an RNG seed and not as
  573. described above. Using the same seed yields the same random shape.
  574. .. ACCEPTS: (scale: float, length: float, randomness: float)
  575. """
  576. if scale is None:
  577. self._sketch = None
  578. else:
  579. self._sketch = (scale, length or 128.0, randomness or 16.0)
  580. self.stale = True
  581. def set_path_effects(self, path_effects):
  582. """
  583. Set the path effects.
  584. Parameters
  585. ----------
  586. path_effects : list of `.AbstractPathEffect`
  587. """
  588. self._path_effects = path_effects
  589. self.stale = True
  590. def get_path_effects(self):
  591. return self._path_effects
  592. def get_figure(self, root=False):
  593. """
  594. Return the `.Figure` or `.SubFigure` instance the artist belongs to.
  595. Parameters
  596. ----------
  597. root : bool, default=False
  598. If False, return the (Sub)Figure this artist is on. If True,
  599. return the root Figure for a nested tree of SubFigures.
  600. """
  601. if root and self._parent_figure is not None:
  602. return self._parent_figure.get_figure(root=True)
  603. return self._parent_figure
  604. def set_figure(self, fig):
  605. """
  606. Set the `.Figure` or `.SubFigure` instance the artist belongs to.
  607. Parameters
  608. ----------
  609. fig : `~matplotlib.figure.Figure` or `~matplotlib.figure.SubFigure`
  610. """
  611. # if this is a no-op just return
  612. if self._parent_figure is fig:
  613. return
  614. # if we currently have a figure (the case of both `self.figure`
  615. # and *fig* being none is taken care of above) we then user is
  616. # trying to change the figure an artist is associated with which
  617. # is not allowed for the same reason as adding the same instance
  618. # to more than one Axes
  619. if self._parent_figure is not None:
  620. raise RuntimeError("Can not put single artist in "
  621. "more than one figure")
  622. self._parent_figure = fig
  623. if self._parent_figure and self._parent_figure is not self:
  624. self.pchanged()
  625. self.stale = True
  626. figure = property(get_figure, set_figure,
  627. doc=("The (Sub)Figure that the artist is on. For more "
  628. "control, use the `get_figure` method."))
  629. def set_clip_box(self, clipbox):
  630. """
  631. Set the artist's clip `.Bbox`.
  632. Parameters
  633. ----------
  634. clipbox : `~matplotlib.transforms.BboxBase` or None
  635. Will typically be created from a `.TransformedBbox`. For instance,
  636. ``TransformedBbox(Bbox([[0, 0], [1, 1]]), ax.transAxes)`` is the default
  637. clipping for an artist added to an Axes.
  638. """
  639. _api.check_isinstance((BboxBase, None), clipbox=clipbox)
  640. if clipbox != self.clipbox:
  641. self.clipbox = clipbox
  642. self.pchanged()
  643. self.stale = True
  644. def set_clip_path(self, path, transform=None):
  645. """
  646. Set the artist's clip path.
  647. Parameters
  648. ----------
  649. path : `~matplotlib.patches.Patch` or `.Path` or `.TransformedPath` or None
  650. The clip path. If given a `.Path`, *transform* must be provided as
  651. well. If *None*, a previously set clip path is removed.
  652. transform : `~matplotlib.transforms.Transform`, optional
  653. Only used if *path* is a `.Path`, in which case the given `.Path`
  654. is converted to a `.TransformedPath` using *transform*.
  655. Notes
  656. -----
  657. For efficiency, if *path* is a `.Rectangle` this method will set the
  658. clipping box to the corresponding rectangle and set the clipping path
  659. to ``None``.
  660. For technical reasons (support of `~.Artist.set`), a tuple
  661. (*path*, *transform*) is also accepted as a single positional
  662. parameter.
  663. .. ACCEPTS: Patch or (Path, Transform) or None
  664. """
  665. from matplotlib.patches import Patch, Rectangle
  666. success = False
  667. if transform is None:
  668. if isinstance(path, Rectangle):
  669. self.clipbox = TransformedBbox(Bbox.unit(),
  670. path.get_transform())
  671. self._clippath = None
  672. success = True
  673. elif isinstance(path, Patch):
  674. self._clippath = TransformedPatchPath(path)
  675. success = True
  676. elif isinstance(path, tuple):
  677. path, transform = path
  678. if path is None:
  679. self._clippath = None
  680. success = True
  681. elif isinstance(path, Path):
  682. self._clippath = TransformedPath(path, transform)
  683. success = True
  684. elif isinstance(path, TransformedPatchPath):
  685. self._clippath = path
  686. success = True
  687. elif isinstance(path, TransformedPath):
  688. self._clippath = path
  689. success = True
  690. if not success:
  691. raise TypeError(
  692. "Invalid arguments to set_clip_path, of type "
  693. f"{type(path).__name__} and {type(transform).__name__}")
  694. # This may result in the callbacks being hit twice, but guarantees they
  695. # will be hit at least once.
  696. self.pchanged()
  697. self.stale = True
  698. def get_alpha(self):
  699. """
  700. Return the alpha value used for blending - not supported on all
  701. backends.
  702. """
  703. return self._alpha
  704. def get_visible(self):
  705. """Return the visibility."""
  706. return self._visible
  707. def get_animated(self):
  708. """Return whether the artist is animated."""
  709. return self._animated
  710. def get_in_layout(self):
  711. """
  712. Return boolean flag, ``True`` if artist is included in layout
  713. calculations.
  714. E.g. :ref:`constrainedlayout_guide`,
  715. `.Figure.tight_layout()`, and
  716. ``fig.savefig(fname, bbox_inches='tight')``.
  717. """
  718. return self._in_layout
  719. def _fully_clipped_to_axes(self):
  720. """
  721. Return a boolean flag, ``True`` if the artist is clipped to the Axes
  722. and can thus be skipped in layout calculations. Requires `get_clip_on`
  723. is True, one of `clip_box` or `clip_path` is set, ``clip_box.extents``
  724. is equivalent to ``ax.bbox.extents`` (if set), and ``clip_path._patch``
  725. is equivalent to ``ax.patch`` (if set).
  726. """
  727. # Note that ``clip_path.get_fully_transformed_path().get_extents()``
  728. # cannot be directly compared to ``axes.bbox.extents`` because the
  729. # extents may be undefined (i.e. equivalent to ``Bbox.null()``)
  730. # before the associated artist is drawn, and this method is meant
  731. # to determine whether ``axes.get_tightbbox()`` may bypass drawing
  732. clip_box = self.get_clip_box()
  733. clip_path = self.get_clip_path()
  734. return (self.axes is not None
  735. and self.get_clip_on()
  736. and (clip_box is not None or clip_path is not None)
  737. and (clip_box is None
  738. or np.all(clip_box.extents == self.axes.bbox.extents))
  739. and (clip_path is None
  740. or isinstance(clip_path, TransformedPatchPath)
  741. and clip_path._patch is self.axes.patch))
  742. def get_clip_on(self):
  743. """Return whether the artist uses clipping."""
  744. return self._clipon
  745. def get_clip_box(self):
  746. """Return the clipbox."""
  747. return self.clipbox
  748. def get_clip_path(self):
  749. """Return the clip path."""
  750. return self._clippath
  751. def get_transformed_clip_path_and_affine(self):
  752. """
  753. Return the clip path with the non-affine part of its
  754. transformation applied, and the remaining affine part of its
  755. transformation.
  756. """
  757. if self._clippath is not None:
  758. return self._clippath.get_transformed_path_and_affine()
  759. return None, None
  760. def set_clip_on(self, b):
  761. """
  762. Set whether the artist uses clipping.
  763. When False, artists will be visible outside the Axes which
  764. can lead to unexpected results.
  765. Parameters
  766. ----------
  767. b : bool
  768. """
  769. self._clipon = b
  770. # This may result in the callbacks being hit twice, but ensures they
  771. # are hit at least once
  772. self.pchanged()
  773. self.stale = True
  774. def _set_gc_clip(self, gc):
  775. """Set the clip properly for the gc."""
  776. if self._clipon:
  777. if self.clipbox is not None:
  778. gc.set_clip_rectangle(self.clipbox)
  779. gc.set_clip_path(self._clippath)
  780. else:
  781. gc.set_clip_rectangle(None)
  782. gc.set_clip_path(None)
  783. def get_rasterized(self):
  784. """Return whether the artist is to be rasterized."""
  785. return self._rasterized
  786. def set_rasterized(self, rasterized):
  787. """
  788. Force rasterized (bitmap) drawing for vector graphics output.
  789. Rasterized drawing is not supported by all artists. If you try to
  790. enable this on an artist that does not support it, the command has no
  791. effect and a warning will be issued.
  792. This setting is ignored for pixel-based output.
  793. See also :doc:`/gallery/misc/rasterization_demo`.
  794. Parameters
  795. ----------
  796. rasterized : bool
  797. """
  798. supports_rasterization = getattr(self.draw,
  799. "_supports_rasterization", False)
  800. if rasterized and not supports_rasterization:
  801. _api.warn_external(f"Rasterization of '{self}' will be ignored")
  802. self._rasterized = rasterized
  803. def get_agg_filter(self):
  804. """Return filter function to be used for agg filter."""
  805. return self._agg_filter
  806. def set_agg_filter(self, filter_func):
  807. """
  808. Set the agg filter.
  809. Parameters
  810. ----------
  811. filter_func : callable
  812. A filter function, which takes a (m, n, depth) float array
  813. and a dpi value, and returns a (m, n, depth) array and two
  814. offsets from the bottom left corner of the image
  815. .. ACCEPTS: a filter function, which takes a (m, n, 3) float array
  816. and a dpi value, and returns a (m, n, 3) array and two offsets
  817. from the bottom left corner of the image
  818. """
  819. self._agg_filter = filter_func
  820. self.stale = True
  821. def draw(self, renderer):
  822. """
  823. Draw the Artist (and its children) using the given renderer.
  824. This has no effect if the artist is not visible (`.Artist.get_visible`
  825. returns False).
  826. Parameters
  827. ----------
  828. renderer : `~matplotlib.backend_bases.RendererBase` subclass.
  829. Notes
  830. -----
  831. This method is overridden in the Artist subclasses.
  832. """
  833. if not self.get_visible():
  834. return
  835. self.stale = False
  836. def set_alpha(self, alpha):
  837. """
  838. Set the alpha value used for blending - not supported on all backends.
  839. Parameters
  840. ----------
  841. alpha : float or None
  842. *alpha* must be within the 0-1 range, inclusive.
  843. """
  844. if alpha is not None and not isinstance(alpha, Real):
  845. raise TypeError(
  846. f'alpha must be numeric or None, not {type(alpha)}')
  847. if alpha is not None and not (0 <= alpha <= 1):
  848. raise ValueError(f'alpha ({alpha}) is outside 0-1 range')
  849. if alpha != self._alpha:
  850. self._alpha = alpha
  851. self.pchanged()
  852. self.stale = True
  853. def _set_alpha_for_array(self, alpha):
  854. """
  855. Set the alpha value used for blending - not supported on all backends.
  856. Parameters
  857. ----------
  858. alpha : array-like or float or None
  859. All values must be within the 0-1 range, inclusive.
  860. Masked values and nans are not supported.
  861. """
  862. if isinstance(alpha, str):
  863. raise TypeError("alpha must be numeric or None, not a string")
  864. if not np.iterable(alpha):
  865. Artist.set_alpha(self, alpha)
  866. return
  867. alpha = np.asarray(alpha)
  868. if not (0 <= alpha.min() and alpha.max() <= 1):
  869. raise ValueError('alpha must be between 0 and 1, inclusive, '
  870. f'but min is {alpha.min()}, max is {alpha.max()}')
  871. self._alpha = alpha
  872. self.pchanged()
  873. self.stale = True
  874. def set_visible(self, b):
  875. """
  876. Set the artist's visibility.
  877. Parameters
  878. ----------
  879. b : bool
  880. """
  881. if b != self._visible:
  882. self._visible = b
  883. self.pchanged()
  884. self.stale = True
  885. def set_animated(self, b):
  886. """
  887. Set whether the artist is intended to be used in an animation.
  888. If True, the artist is excluded from regular drawing of the figure.
  889. You have to call `.Figure.draw_artist` / `.Axes.draw_artist`
  890. explicitly on the artist. This approach is used to speed up animations
  891. using blitting.
  892. See also `matplotlib.animation` and
  893. :ref:`blitting`.
  894. Parameters
  895. ----------
  896. b : bool
  897. """
  898. if self._animated != b:
  899. self._animated = b
  900. self.pchanged()
  901. def set_in_layout(self, in_layout):
  902. """
  903. Set if artist is to be included in layout calculations,
  904. E.g. :ref:`constrainedlayout_guide`,
  905. `.Figure.tight_layout()`, and
  906. ``fig.savefig(fname, bbox_inches='tight')``.
  907. Parameters
  908. ----------
  909. in_layout : bool
  910. """
  911. self._in_layout = in_layout
  912. def get_label(self):
  913. """Return the label used for this artist in the legend."""
  914. return self._label
  915. def set_label(self, s):
  916. """
  917. Set a label that will be displayed in the legend.
  918. Parameters
  919. ----------
  920. s : object
  921. *s* will be converted to a string by calling `str`.
  922. """
  923. label = str(s) if s is not None else None
  924. if label != self._label:
  925. self._label = label
  926. self.pchanged()
  927. self.stale = True
  928. def get_zorder(self):
  929. """Return the artist's zorder."""
  930. return self.zorder
  931. def set_zorder(self, level):
  932. """
  933. Set the zorder for the artist. Artists with lower zorder
  934. values are drawn first.
  935. Parameters
  936. ----------
  937. level : float
  938. """
  939. if level is None:
  940. level = self.__class__.zorder
  941. if level != self.zorder:
  942. self.zorder = level
  943. self.pchanged()
  944. self.stale = True
  945. @property
  946. def sticky_edges(self):
  947. """
  948. ``x`` and ``y`` sticky edge lists for autoscaling.
  949. When performing autoscaling, if a data limit coincides with a value in
  950. the corresponding sticky_edges list, then no margin will be added--the
  951. view limit "sticks" to the edge. A typical use case is histograms,
  952. where one usually expects no margin on the bottom edge (0) of the
  953. histogram.
  954. Moreover, margin expansion "bumps" against sticky edges and cannot
  955. cross them. For example, if the upper data limit is 1.0, the upper
  956. view limit computed by simple margin application is 1.2, but there is a
  957. sticky edge at 1.1, then the actual upper view limit will be 1.1.
  958. This attribute cannot be assigned to; however, the ``x`` and ``y``
  959. lists can be modified in place as needed.
  960. Examples
  961. --------
  962. >>> artist.sticky_edges.x[:] = (xmin, xmax)
  963. >>> artist.sticky_edges.y[:] = (ymin, ymax)
  964. """
  965. return self._sticky_edges
  966. def update_from(self, other):
  967. """Copy properties from *other* to *self*."""
  968. self._transform = other._transform
  969. self._transformSet = other._transformSet
  970. self._visible = other._visible
  971. self._alpha = other._alpha
  972. self.clipbox = other.clipbox
  973. self._clipon = other._clipon
  974. self._clippath = other._clippath
  975. self._label = other._label
  976. self._sketch = other._sketch
  977. self._path_effects = other._path_effects
  978. self.sticky_edges.x[:] = other.sticky_edges.x.copy()
  979. self.sticky_edges.y[:] = other.sticky_edges.y.copy()
  980. self.pchanged()
  981. self.stale = True
  982. def properties(self):
  983. """Return a dictionary of all the properties of the artist."""
  984. return ArtistInspector(self).properties()
  985. def _update_props(self, props, errfmt):
  986. """
  987. Helper for `.Artist.set` and `.Artist.update`.
  988. *errfmt* is used to generate error messages for invalid property
  989. names; it gets formatted with ``type(self)`` for "{cls}" and the
  990. property name for "{prop_name}".
  991. """
  992. ret = []
  993. with cbook._setattr_cm(self, eventson=False):
  994. for k, v in props.items():
  995. # Allow attributes we want to be able to update through
  996. # art.update, art.set, setp.
  997. if k == "axes":
  998. ret.append(setattr(self, k, v))
  999. else:
  1000. func = getattr(self, f"set_{k}", None)
  1001. if not callable(func):
  1002. raise AttributeError(
  1003. errfmt.format(cls=type(self), prop_name=k),
  1004. name=k)
  1005. ret.append(func(v))
  1006. if ret:
  1007. self.pchanged()
  1008. self.stale = True
  1009. return ret
  1010. def update(self, props):
  1011. """
  1012. Update this artist's properties from the dict *props*.
  1013. Parameters
  1014. ----------
  1015. props : dict
  1016. """
  1017. return self._update_props(
  1018. props, "{cls.__name__!r} object has no property {prop_name!r}")
  1019. def _internal_update(self, kwargs):
  1020. """
  1021. Update artist properties without prenormalizing them, but generating
  1022. errors as if calling `set`.
  1023. The lack of prenormalization is to maintain backcompatibility.
  1024. """
  1025. return self._update_props(
  1026. kwargs, "{cls.__name__}.set() got an unexpected keyword argument "
  1027. "{prop_name!r}")
  1028. def set(self, **kwargs):
  1029. # docstring and signature are auto-generated via
  1030. # Artist._update_set_signature_and_docstring() at the end of the
  1031. # module.
  1032. return self._internal_update(cbook.normalize_kwargs(kwargs, self))
  1033. @contextlib.contextmanager
  1034. def _cm_set(self, **kwargs):
  1035. """
  1036. `.Artist.set` context-manager that restores original values at exit.
  1037. """
  1038. orig_vals = {k: getattr(self, f"get_{k}")() for k in kwargs}
  1039. try:
  1040. self.set(**kwargs)
  1041. yield
  1042. finally:
  1043. self.set(**orig_vals)
  1044. def findobj(self, match=None, include_self=True):
  1045. """
  1046. Find artist objects.
  1047. Recursively find all `.Artist` instances contained in the artist.
  1048. Parameters
  1049. ----------
  1050. match
  1051. A filter criterion for the matches. This can be
  1052. - *None*: Return all objects contained in artist.
  1053. - A function with signature ``def match(artist: Artist) -> bool``.
  1054. The result will only contain artists for which the function
  1055. returns *True*.
  1056. - A class instance: e.g., `.Line2D`. The result will only contain
  1057. artists of this class or its subclasses (``isinstance`` check).
  1058. include_self : bool
  1059. Include *self* in the list to be checked for a match.
  1060. Returns
  1061. -------
  1062. list of `.Artist`
  1063. """
  1064. if match is None: # always return True
  1065. def matchfunc(x):
  1066. return True
  1067. elif isinstance(match, type) and issubclass(match, Artist):
  1068. def matchfunc(x):
  1069. return isinstance(x, match)
  1070. elif callable(match):
  1071. matchfunc = match
  1072. else:
  1073. raise ValueError('match must be None, a matplotlib.artist.Artist '
  1074. 'subclass, or a callable')
  1075. artists = reduce(operator.iadd,
  1076. [c.findobj(matchfunc) for c in self.get_children()], [])
  1077. if include_self and matchfunc(self):
  1078. artists.append(self)
  1079. return artists
  1080. def get_cursor_data(self, event):
  1081. """
  1082. Return the cursor data for a given event.
  1083. .. note::
  1084. This method is intended to be overridden by artist subclasses.
  1085. As an end-user of Matplotlib you will most likely not call this
  1086. method yourself.
  1087. Cursor data can be used by Artists to provide additional context
  1088. information for a given event. The default implementation just returns
  1089. *None*.
  1090. Subclasses can override the method and return arbitrary data. However,
  1091. when doing so, they must ensure that `.format_cursor_data` can convert
  1092. the data to a string representation.
  1093. The only current use case is displaying the z-value of an `.AxesImage`
  1094. in the status bar of a plot window, while moving the mouse.
  1095. Parameters
  1096. ----------
  1097. event : `~matplotlib.backend_bases.MouseEvent`
  1098. See Also
  1099. --------
  1100. format_cursor_data
  1101. """
  1102. return None
  1103. def format_cursor_data(self, data):
  1104. """
  1105. Return a string representation of *data*.
  1106. .. note::
  1107. This method is intended to be overridden by artist subclasses.
  1108. As an end-user of Matplotlib you will most likely not call this
  1109. method yourself.
  1110. The default implementation converts ints and floats and arrays of ints
  1111. and floats into a comma-separated string enclosed in square brackets,
  1112. unless the artist has an associated colorbar, in which case scalar
  1113. values are formatted using the colorbar's formatter.
  1114. See Also
  1115. --------
  1116. get_cursor_data
  1117. """
  1118. if np.ndim(data) == 0 and hasattr(self, "_format_cursor_data_override"):
  1119. # workaround for ScalarMappable to be able to define its own
  1120. # format_cursor_data(). See ScalarMappable._format_cursor_data_override
  1121. # for details.
  1122. return self._format_cursor_data_override(data)
  1123. else:
  1124. try:
  1125. data[0]
  1126. except (TypeError, IndexError):
  1127. data = [data]
  1128. data_str = ', '.join(f'{item:0.3g}' for item in data
  1129. if isinstance(item, Number))
  1130. return "[" + data_str + "]"
  1131. def get_mouseover(self):
  1132. """
  1133. Return whether this artist is queried for custom context information
  1134. when the mouse cursor moves over it.
  1135. """
  1136. return self._mouseover
  1137. def set_mouseover(self, mouseover):
  1138. """
  1139. Set whether this artist is queried for custom context information when
  1140. the mouse cursor moves over it.
  1141. Parameters
  1142. ----------
  1143. mouseover : bool
  1144. See Also
  1145. --------
  1146. get_cursor_data
  1147. .ToolCursorPosition
  1148. .NavigationToolbar2
  1149. """
  1150. self._mouseover = bool(mouseover)
  1151. ax = self.axes
  1152. if ax:
  1153. if self._mouseover:
  1154. ax._mouseover_set.add(self)
  1155. else:
  1156. ax._mouseover_set.discard(self)
  1157. mouseover = property(get_mouseover, set_mouseover) # backcompat.
  1158. def _get_tightbbox_for_layout_only(obj, *args, **kwargs):
  1159. """
  1160. Matplotlib's `.Axes.get_tightbbox` and `.Axis.get_tightbbox` support a
  1161. *for_layout_only* kwarg; this helper tries to use the kwarg but skips it
  1162. when encountering third-party subclasses that do not support it.
  1163. """
  1164. try:
  1165. return obj.get_tightbbox(*args, **{**kwargs, "for_layout_only": True})
  1166. except TypeError:
  1167. return obj.get_tightbbox(*args, **kwargs)
  1168. class ArtistInspector:
  1169. """
  1170. A helper class to inspect an `~matplotlib.artist.Artist` and return
  1171. information about its settable properties and their current values.
  1172. """
  1173. def __init__(self, o):
  1174. r"""
  1175. Initialize the artist inspector with an `Artist` or an iterable of
  1176. `Artist`\s. If an iterable is used, we assume it is a homogeneous
  1177. sequence (all `Artist`\s are of the same type) and it is your
  1178. responsibility to make sure this is so.
  1179. """
  1180. if not isinstance(o, Artist):
  1181. if np.iterable(o):
  1182. o = list(o)
  1183. if len(o):
  1184. o = o[0]
  1185. self.oorig = o
  1186. if not isinstance(o, type):
  1187. o = type(o)
  1188. self.o = o
  1189. self.aliasd = self.get_aliases()
  1190. def get_aliases(self):
  1191. """
  1192. Get a dict mapping property fullnames to sets of aliases for each alias
  1193. in the :class:`~matplotlib.artist.ArtistInspector`.
  1194. e.g., for lines::
  1195. {'markerfacecolor': {'mfc'},
  1196. 'linewidth' : {'lw'},
  1197. }
  1198. """
  1199. names = [name for name in dir(self.o)
  1200. if name.startswith(('set_', 'get_'))
  1201. and callable(getattr(self.o, name))]
  1202. aliases = {}
  1203. for name in names:
  1204. func = getattr(self.o, name)
  1205. if not self.is_alias(func):
  1206. continue
  1207. propname = re.search(f"`({name[:4]}.*)`", # get_.*/set_.*
  1208. inspect.getdoc(func)).group(1)
  1209. aliases.setdefault(propname[4:], set()).add(name[4:])
  1210. return aliases
  1211. _get_valid_values_regex = re.compile(
  1212. r"\n\s*(?:\.\.\s+)?ACCEPTS:\s*((?:.|\n)*?)(?:$|(?:\n\n))"
  1213. )
  1214. def get_valid_values(self, attr):
  1215. """
  1216. Get the legal arguments for the setter associated with *attr*.
  1217. This is done by querying the docstring of the setter for a line that
  1218. begins with "ACCEPTS:" or ".. ACCEPTS:", and then by looking for a
  1219. numpydoc-style documentation for the setter's first argument.
  1220. """
  1221. name = 'set_%s' % attr
  1222. if not hasattr(self.o, name):
  1223. raise AttributeError(f'{self.o} has no function {name}')
  1224. func = getattr(self.o, name)
  1225. if hasattr(func, '_kwarg_doc'):
  1226. return func._kwarg_doc
  1227. docstring = inspect.getdoc(func)
  1228. if docstring is None:
  1229. return 'unknown'
  1230. if docstring.startswith('Alias for '):
  1231. return None
  1232. match = self._get_valid_values_regex.search(docstring)
  1233. if match is not None:
  1234. return re.sub("\n *", " ", match.group(1))
  1235. # Much faster than list(inspect.signature(func).parameters)[1],
  1236. # although barely relevant wrt. matplotlib's total import time.
  1237. param_name = func.__code__.co_varnames[1]
  1238. # We could set the presence * based on whether the parameter is a
  1239. # varargs (it can't be a varkwargs) but it's not really worth it.
  1240. match = re.search(fr"(?m)^ *\*?{param_name} : (.+)", docstring)
  1241. if match:
  1242. return match.group(1)
  1243. return 'unknown'
  1244. def _replace_path(self, source_class):
  1245. """
  1246. Changes the full path to the public API path that is used
  1247. in sphinx. This is needed for links to work.
  1248. """
  1249. replace_dict = {'_base._AxesBase': 'Axes',
  1250. '_axes.Axes': 'Axes'}
  1251. for key, value in replace_dict.items():
  1252. source_class = source_class.replace(key, value)
  1253. return source_class
  1254. def get_setters(self):
  1255. """
  1256. Get the attribute strings with setters for object.
  1257. For example, for a line, return ``['markerfacecolor', 'linewidth',
  1258. ....]``.
  1259. """
  1260. setters = []
  1261. for name in dir(self.o):
  1262. if not name.startswith('set_'):
  1263. continue
  1264. func = getattr(self.o, name)
  1265. if (not callable(func)
  1266. or self.number_of_parameters(func) < 2
  1267. or self.is_alias(func)):
  1268. continue
  1269. setters.append(name[4:])
  1270. return setters
  1271. @staticmethod
  1272. @cache
  1273. def number_of_parameters(func):
  1274. """Return number of parameters of the callable *func*."""
  1275. return len(inspect.signature(func).parameters)
  1276. @staticmethod
  1277. @cache
  1278. def is_alias(method):
  1279. """
  1280. Return whether the object *method* is an alias for another method.
  1281. """
  1282. ds = inspect.getdoc(method)
  1283. if ds is None:
  1284. return False
  1285. return ds.startswith('Alias for ')
  1286. def aliased_name(self, s):
  1287. """
  1288. Return 'PROPNAME or alias' if *s* has an alias, else return 'PROPNAME'.
  1289. For example, for the line markerfacecolor property, which has an
  1290. alias, return 'markerfacecolor or mfc' and for the transform
  1291. property, which does not, return 'transform'.
  1292. """
  1293. aliases = ''.join(' or %s' % x for x in sorted(self.aliasd.get(s, [])))
  1294. return s + aliases
  1295. _NOT_LINKABLE = {
  1296. # A set of property setter methods that are not available in our
  1297. # current docs. This is a workaround used to prevent trying to link
  1298. # these setters which would lead to "target reference not found"
  1299. # warnings during doc build.
  1300. 'matplotlib.image._ImageBase.set_alpha',
  1301. 'matplotlib.image._ImageBase.set_array',
  1302. 'matplotlib.image._ImageBase.set_data',
  1303. 'matplotlib.image._ImageBase.set_filternorm',
  1304. 'matplotlib.image._ImageBase.set_filterrad',
  1305. 'matplotlib.image._ImageBase.set_interpolation',
  1306. 'matplotlib.image._ImageBase.set_interpolation_stage',
  1307. 'matplotlib.image._ImageBase.set_resample',
  1308. 'matplotlib.text._AnnotationBase.set_annotation_clip',
  1309. }
  1310. def aliased_name_rest(self, s, target):
  1311. """
  1312. Return 'PROPNAME or alias' if *s* has an alias, else return 'PROPNAME',
  1313. formatted for reST.
  1314. For example, for the line markerfacecolor property, which has an
  1315. alias, return 'markerfacecolor or mfc' and for the transform
  1316. property, which does not, return 'transform'.
  1317. """
  1318. # workaround to prevent "reference target not found"
  1319. if target in self._NOT_LINKABLE:
  1320. return f'``{s}``'
  1321. aliases = ''.join(
  1322. f' or :meth:`{a} <{target}>`' for a in sorted(self.aliasd.get(s, [])))
  1323. return f':meth:`{s} <{target}>`{aliases}'
  1324. def pprint_setters(self, prop=None, leadingspace=2):
  1325. """
  1326. If *prop* is *None*, return a list of strings of all settable
  1327. properties and their valid values.
  1328. If *prop* is not *None*, it is a valid property name and that
  1329. property will be returned as a string of property : valid
  1330. values.
  1331. """
  1332. if leadingspace:
  1333. pad = ' ' * leadingspace
  1334. else:
  1335. pad = ''
  1336. if prop is not None:
  1337. accepts = self.get_valid_values(prop)
  1338. return f'{pad}{prop}: {accepts}'
  1339. lines = []
  1340. for prop in sorted(self.get_setters()):
  1341. accepts = self.get_valid_values(prop)
  1342. name = self.aliased_name(prop)
  1343. lines.append(f'{pad}{name}: {accepts}')
  1344. return lines
  1345. def pprint_setters_rest(self, prop=None, leadingspace=4):
  1346. """
  1347. If *prop* is *None*, return a list of reST-formatted strings of all
  1348. settable properties and their valid values.
  1349. If *prop* is not *None*, it is a valid property name and that
  1350. property will be returned as a string of "property : valid"
  1351. values.
  1352. """
  1353. if leadingspace:
  1354. pad = ' ' * leadingspace
  1355. else:
  1356. pad = ''
  1357. if prop is not None:
  1358. accepts = self.get_valid_values(prop)
  1359. return f'{pad}{prop}: {accepts}'
  1360. prop_and_qualnames = []
  1361. for prop in sorted(self.get_setters()):
  1362. # Find the parent method which actually provides the docstring.
  1363. for cls in self.o.__mro__:
  1364. method = getattr(cls, f"set_{prop}", None)
  1365. if method and method.__doc__ is not None:
  1366. break
  1367. else: # No docstring available.
  1368. method = getattr(self.o, f"set_{prop}")
  1369. prop_and_qualnames.append(
  1370. (prop, f"{method.__module__}.{method.__qualname__}"))
  1371. names = [self.aliased_name_rest(prop, target)
  1372. .replace('_base._AxesBase', 'Axes')
  1373. .replace('_axes.Axes', 'Axes')
  1374. for prop, target in prop_and_qualnames]
  1375. accepts = [self.get_valid_values(prop)
  1376. for prop, _ in prop_and_qualnames]
  1377. col0_len = max(len(n) for n in names)
  1378. col1_len = max(len(a) for a in accepts)
  1379. table_formatstr = pad + ' ' + '=' * col0_len + ' ' + '=' * col1_len
  1380. return [
  1381. '',
  1382. pad + '.. table::',
  1383. pad + ' :class: property-table',
  1384. '',
  1385. table_formatstr,
  1386. pad + ' ' + 'Property'.ljust(col0_len)
  1387. + ' ' + 'Description'.ljust(col1_len),
  1388. table_formatstr,
  1389. *[pad + ' ' + n.ljust(col0_len) + ' ' + a.ljust(col1_len)
  1390. for n, a in zip(names, accepts)],
  1391. table_formatstr,
  1392. '',
  1393. ]
  1394. def properties(self):
  1395. """Return a dictionary mapping property name -> value."""
  1396. o = self.oorig
  1397. getters = [name for name in dir(o)
  1398. if name.startswith('get_') and callable(getattr(o, name))]
  1399. getters.sort()
  1400. d = {}
  1401. for name in getters:
  1402. func = getattr(o, name)
  1403. if self.is_alias(func):
  1404. continue
  1405. try:
  1406. with warnings.catch_warnings():
  1407. warnings.simplefilter('ignore')
  1408. val = func()
  1409. except Exception:
  1410. continue
  1411. else:
  1412. d[name[4:]] = val
  1413. return d
  1414. def pprint_getters(self):
  1415. """Return the getters and actual values as list of strings."""
  1416. lines = []
  1417. for name, val in sorted(self.properties().items()):
  1418. if getattr(val, 'shape', ()) != () and len(val) > 6:
  1419. s = str(val[:6]) + '...'
  1420. else:
  1421. s = str(val)
  1422. s = s.replace('\n', ' ')
  1423. if len(s) > 50:
  1424. s = s[:50] + '...'
  1425. name = self.aliased_name(name)
  1426. lines.append(f' {name} = {s}')
  1427. return lines
  1428. def getp(obj, property=None):
  1429. """
  1430. Return the value of an `.Artist`'s *property*, or print all of them.
  1431. Parameters
  1432. ----------
  1433. obj : `~matplotlib.artist.Artist`
  1434. The queried artist; e.g., a `.Line2D`, a `.Text`, or an `~.axes.Axes`.
  1435. property : str or None, default: None
  1436. If *property* is 'somename', this function returns
  1437. ``obj.get_somename()``.
  1438. If it's None (or unset), it *prints* all gettable properties from
  1439. *obj*. Many properties have aliases for shorter typing, e.g. 'lw' is
  1440. an alias for 'linewidth'. In the output, aliases and full property
  1441. names will be listed as:
  1442. property or alias = value
  1443. e.g.:
  1444. linewidth or lw = 2
  1445. See Also
  1446. --------
  1447. setp
  1448. """
  1449. if property is None:
  1450. insp = ArtistInspector(obj)
  1451. ret = insp.pprint_getters()
  1452. print('\n'.join(ret))
  1453. return
  1454. return getattr(obj, 'get_' + property)()
  1455. # alias
  1456. get = getp
  1457. def setp(obj, *args, file=None, **kwargs):
  1458. """
  1459. Set one or more properties on an `.Artist`, or list allowed values.
  1460. Parameters
  1461. ----------
  1462. obj : `~matplotlib.artist.Artist` or list of `.Artist`
  1463. The artist(s) whose properties are being set or queried. When setting
  1464. properties, all artists are affected; when querying the allowed values,
  1465. only the first instance in the sequence is queried.
  1466. For example, two lines can be made thicker and red with a single call:
  1467. >>> x = arange(0, 1, 0.01)
  1468. >>> lines = plot(x, sin(2*pi*x), x, sin(4*pi*x))
  1469. >>> setp(lines, linewidth=2, color='r')
  1470. file : file-like, default: `sys.stdout`
  1471. Where `setp` writes its output when asked to list allowed values.
  1472. >>> with open('output.log') as file:
  1473. ... setp(line, file=file)
  1474. The default, ``None``, means `sys.stdout`.
  1475. *args, **kwargs
  1476. The properties to set. The following combinations are supported:
  1477. - Set the linestyle of a line to be dashed:
  1478. >>> line, = plot([1, 2, 3])
  1479. >>> setp(line, linestyle='--')
  1480. - Set multiple properties at once:
  1481. >>> setp(line, linewidth=2, color='r')
  1482. - List allowed values for a line's linestyle:
  1483. >>> setp(line, 'linestyle')
  1484. linestyle: {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
  1485. - List all properties that can be set, and their allowed values:
  1486. >>> setp(line)
  1487. agg_filter: a filter function, ...
  1488. [long output listing omitted]
  1489. `setp` also supports MATLAB style string/value pairs. For example, the
  1490. following are equivalent:
  1491. >>> setp(lines, 'linewidth', 2, 'color', 'r') # MATLAB style
  1492. >>> setp(lines, linewidth=2, color='r') # Python style
  1493. See Also
  1494. --------
  1495. getp
  1496. """
  1497. if isinstance(obj, Artist):
  1498. objs = [obj]
  1499. else:
  1500. objs = list(cbook.flatten(obj))
  1501. if not objs:
  1502. return
  1503. insp = ArtistInspector(objs[0])
  1504. if not kwargs and len(args) < 2:
  1505. if args:
  1506. print(insp.pprint_setters(prop=args[0]), file=file)
  1507. else:
  1508. print('\n'.join(insp.pprint_setters()), file=file)
  1509. return
  1510. if len(args) % 2:
  1511. raise ValueError('The set args must be string, value pairs')
  1512. funcvals = dict(zip(args[::2], args[1::2]))
  1513. ret = [o.update(funcvals) for o in objs] + [o.set(**kwargs) for o in objs]
  1514. return list(cbook.flatten(ret))
  1515. def kwdoc(artist):
  1516. r"""
  1517. Inspect an `~matplotlib.artist.Artist` class (using `.ArtistInspector`) and
  1518. return information about its settable properties and their current values.
  1519. Parameters
  1520. ----------
  1521. artist : `~matplotlib.artist.Artist` or an iterable of `Artist`\s
  1522. Returns
  1523. -------
  1524. str
  1525. The settable properties of *artist*, as plain text if
  1526. :rc:`docstring.hardcopy` is False and as a rst table (intended for
  1527. use in Sphinx) if it is True.
  1528. """
  1529. ai = ArtistInspector(artist)
  1530. return ('\n'.join(ai.pprint_setters_rest(leadingspace=4))
  1531. if mpl.rcParams['docstring.hardcopy'] else
  1532. 'Properties:\n' + '\n'.join(ai.pprint_setters(leadingspace=4)))
  1533. # We defer this to the end of them module, because it needs ArtistInspector
  1534. # to be defined.
  1535. Artist._update_set_signature_and_docstring()