artist.py 53 KB

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