artist.py 62 KB

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