artist.py 52 KB

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