spines.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. from collections.abc import MutableMapping
  2. import functools
  3. import numpy as np
  4. import matplotlib as mpl
  5. from matplotlib import _api, _docstring
  6. from matplotlib.artist import allow_rasterization
  7. import matplotlib.transforms as mtransforms
  8. import matplotlib.patches as mpatches
  9. import matplotlib.path as mpath
  10. class Spine(mpatches.Patch):
  11. """
  12. An axis spine -- the line noting the data area boundaries.
  13. Spines are the lines connecting the axis tick marks and noting the
  14. boundaries of the data area. They can be placed at arbitrary
  15. positions. See `~.Spine.set_position` for more information.
  16. The default position is ``('outward', 0)``.
  17. Spines are subclasses of `.Patch`, and inherit much of their behavior.
  18. Spines draw a line, a circle, or an arc depending on if
  19. `~.Spine.set_patch_line`, `~.Spine.set_patch_circle`, or
  20. `~.Spine.set_patch_arc` has been called. Line-like is the default.
  21. For examples see :ref:`spines_examples`.
  22. """
  23. def __str__(self):
  24. return "Spine"
  25. @_docstring.interpd
  26. def __init__(self, axes, spine_type, path, **kwargs):
  27. """
  28. Parameters
  29. ----------
  30. axes : `~matplotlib.axes.Axes`
  31. The `~.axes.Axes` instance containing the spine.
  32. spine_type : str
  33. The spine type.
  34. path : `~matplotlib.path.Path`
  35. The `.Path` instance used to draw the spine.
  36. Other Parameters
  37. ----------------
  38. **kwargs
  39. Valid keyword arguments are:
  40. %(Patch:kwdoc)s
  41. """
  42. super().__init__(**kwargs)
  43. self.axes = axes
  44. self.set_figure(self.axes.get_figure(root=False))
  45. self.spine_type = spine_type
  46. self.set_facecolor('none')
  47. self.set_edgecolor(mpl.rcParams['axes.edgecolor'])
  48. self.set_linewidth(mpl.rcParams['axes.linewidth'])
  49. self.set_capstyle('projecting')
  50. self.axis = None
  51. self.set_zorder(2.5)
  52. self.set_transform(self.axes.transData) # default transform
  53. self._bounds = None # default bounds
  54. # Defer initial position determination. (Not much support for
  55. # non-rectangular axes is currently implemented, and this lets
  56. # them pass through the spines machinery without errors.)
  57. self._position = None
  58. _api.check_isinstance(mpath.Path, path=path)
  59. self._path = path
  60. # To support drawing both linear and circular spines, this
  61. # class implements Patch behavior three ways. If
  62. # self._patch_type == 'line', behave like a mpatches.PathPatch
  63. # instance. If self._patch_type == 'circle', behave like a
  64. # mpatches.Ellipse instance. If self._patch_type == 'arc', behave like
  65. # a mpatches.Arc instance.
  66. self._patch_type = 'line'
  67. # Behavior copied from mpatches.Ellipse:
  68. # Note: This cannot be calculated until this is added to an Axes
  69. self._patch_transform = mtransforms.IdentityTransform()
  70. def set_patch_arc(self, center, radius, theta1, theta2):
  71. """Set the spine to be arc-like."""
  72. self._patch_type = 'arc'
  73. self._center = center
  74. self._width = radius * 2
  75. self._height = radius * 2
  76. self._theta1 = theta1
  77. self._theta2 = theta2
  78. self._path = mpath.Path.arc(theta1, theta2)
  79. # arc drawn on axes transform
  80. self.set_transform(self.axes.transAxes)
  81. self.stale = True
  82. def set_patch_circle(self, center, radius):
  83. """Set the spine to be circular."""
  84. self._patch_type = 'circle'
  85. self._center = center
  86. self._width = radius * 2
  87. self._height = radius * 2
  88. # circle drawn on axes transform
  89. self.set_transform(self.axes.transAxes)
  90. self.stale = True
  91. def set_patch_line(self):
  92. """Set the spine to be linear."""
  93. self._patch_type = 'line'
  94. self.stale = True
  95. # Behavior copied from mpatches.Ellipse:
  96. def _recompute_transform(self):
  97. """
  98. Notes
  99. -----
  100. This cannot be called until after this has been added to an Axes,
  101. otherwise unit conversion will fail. This makes it very important to
  102. call the accessor method and not directly access the transformation
  103. member variable.
  104. """
  105. assert self._patch_type in ('arc', 'circle')
  106. center = (self.convert_xunits(self._center[0]),
  107. self.convert_yunits(self._center[1]))
  108. width = self.convert_xunits(self._width)
  109. height = self.convert_yunits(self._height)
  110. self._patch_transform = mtransforms.Affine2D() \
  111. .scale(width * 0.5, height * 0.5) \
  112. .translate(*center)
  113. def get_patch_transform(self):
  114. if self._patch_type in ('arc', 'circle'):
  115. self._recompute_transform()
  116. return self._patch_transform
  117. else:
  118. return super().get_patch_transform()
  119. def get_window_extent(self, renderer=None):
  120. """
  121. Return the window extent of the spines in display space, including
  122. padding for ticks (but not their labels)
  123. See Also
  124. --------
  125. matplotlib.axes.Axes.get_tightbbox
  126. matplotlib.axes.Axes.get_window_extent
  127. """
  128. # make sure the location is updated so that transforms etc are correct:
  129. self._adjust_location()
  130. bb = super().get_window_extent(renderer=renderer)
  131. if self.axis is None or not self.axis.get_visible():
  132. return bb
  133. bboxes = [bb]
  134. drawn_ticks = self.axis._update_ticks()
  135. major_tick = next(iter({*drawn_ticks} & {*self.axis.majorTicks}), None)
  136. minor_tick = next(iter({*drawn_ticks} & {*self.axis.minorTicks}), None)
  137. for tick in [major_tick, minor_tick]:
  138. if tick is None:
  139. continue
  140. bb0 = bb.frozen()
  141. tickl = tick._size
  142. tickdir = tick._tickdir
  143. if tickdir == 'out':
  144. padout = 1
  145. padin = 0
  146. elif tickdir == 'in':
  147. padout = 0
  148. padin = 1
  149. else:
  150. padout = 0.5
  151. padin = 0.5
  152. dpi = self.get_figure(root=True).dpi
  153. padout = padout * tickl / 72 * dpi
  154. padin = padin * tickl / 72 * dpi
  155. if tick.tick1line.get_visible():
  156. if self.spine_type == 'left':
  157. bb0.x0 = bb0.x0 - padout
  158. bb0.x1 = bb0.x1 + padin
  159. elif self.spine_type == 'bottom':
  160. bb0.y0 = bb0.y0 - padout
  161. bb0.y1 = bb0.y1 + padin
  162. if tick.tick2line.get_visible():
  163. if self.spine_type == 'right':
  164. bb0.x1 = bb0.x1 + padout
  165. bb0.x0 = bb0.x0 - padin
  166. elif self.spine_type == 'top':
  167. bb0.y1 = bb0.y1 + padout
  168. bb0.y0 = bb0.y0 - padout
  169. bboxes.append(bb0)
  170. return mtransforms.Bbox.union(bboxes)
  171. def get_path(self):
  172. return self._path
  173. def _ensure_position_is_set(self):
  174. if self._position is None:
  175. # default position
  176. self._position = ('outward', 0.0) # in points
  177. self.set_position(self._position)
  178. def register_axis(self, axis):
  179. """
  180. Register an axis.
  181. An axis should be registered with its corresponding spine from
  182. the Axes instance. This allows the spine to clear any axis
  183. properties when needed.
  184. """
  185. self.axis = axis
  186. self.stale = True
  187. def clear(self):
  188. """Clear the current spine."""
  189. self._clear()
  190. if self.axis is not None:
  191. self.axis.clear()
  192. def _clear(self):
  193. """
  194. Clear things directly related to the spine.
  195. In this way it is possible to avoid clearing the Axis as well when calling
  196. from library code where it is known that the Axis is cleared separately.
  197. """
  198. self._position = None # clear position
  199. def _adjust_location(self):
  200. """Automatically set spine bounds to the view interval."""
  201. if self.spine_type == 'circle':
  202. return
  203. if self._bounds is not None:
  204. low, high = self._bounds
  205. elif self.spine_type in ('left', 'right'):
  206. low, high = self.axes.viewLim.intervaly
  207. elif self.spine_type in ('top', 'bottom'):
  208. low, high = self.axes.viewLim.intervalx
  209. else:
  210. raise ValueError(f'unknown spine spine_type: {self.spine_type}')
  211. if self._patch_type == 'arc':
  212. if self.spine_type in ('bottom', 'top'):
  213. try:
  214. direction = self.axes.get_theta_direction()
  215. except AttributeError:
  216. direction = 1
  217. try:
  218. offset = self.axes.get_theta_offset()
  219. except AttributeError:
  220. offset = 0
  221. low = low * direction + offset
  222. high = high * direction + offset
  223. if low > high:
  224. low, high = high, low
  225. self._path = mpath.Path.arc(np.rad2deg(low), np.rad2deg(high))
  226. if self.spine_type == 'bottom':
  227. if self.axis is None:
  228. tr = mtransforms.IdentityTransform()
  229. else:
  230. tr = self.axis.get_transform()
  231. rmin, rmax = tr.transform(self.axes.viewLim.intervaly)
  232. try:
  233. rorigin = self.axes.get_rorigin()
  234. except AttributeError:
  235. rorigin = rmin
  236. else:
  237. rorigin = tr.transform(rorigin)
  238. scaled_diameter = (rmin - rorigin) / (rmax - rorigin)
  239. self._height = scaled_diameter
  240. self._width = scaled_diameter
  241. else:
  242. raise ValueError('unable to set bounds for spine "%s"' %
  243. self.spine_type)
  244. else:
  245. v1 = self._path.vertices
  246. assert v1.shape == (2, 2), 'unexpected vertices shape'
  247. if self.spine_type in ['left', 'right']:
  248. v1[0, 1] = low
  249. v1[1, 1] = high
  250. elif self.spine_type in ['bottom', 'top']:
  251. v1[0, 0] = low
  252. v1[1, 0] = high
  253. else:
  254. raise ValueError('unable to set bounds for spine "%s"' %
  255. self.spine_type)
  256. @allow_rasterization
  257. def draw(self, renderer):
  258. self._adjust_location()
  259. ret = super().draw(renderer)
  260. self.stale = False
  261. return ret
  262. def set_position(self, position):
  263. """
  264. Set the position of the spine.
  265. Spine position is specified by a 2 tuple of (position type,
  266. amount). The position types are:
  267. * 'outward': place the spine out from the data area by the specified
  268. number of points. (Negative values place the spine inwards.)
  269. * 'axes': place the spine at the specified Axes coordinate (0 to 1).
  270. * 'data': place the spine at the specified data coordinate.
  271. Additionally, shorthand notations define a special positions:
  272. * 'center' -> ``('axes', 0.5)``
  273. * 'zero' -> ``('data', 0.0)``
  274. Examples
  275. --------
  276. :doc:`/gallery/spines/spine_placement_demo`
  277. """
  278. if position in ('center', 'zero'): # special positions
  279. pass
  280. else:
  281. if len(position) != 2:
  282. raise ValueError("position should be 'center' or 2-tuple")
  283. if position[0] not in ['outward', 'axes', 'data']:
  284. raise ValueError("position[0] should be one of 'outward', "
  285. "'axes', or 'data' ")
  286. self._position = position
  287. self.set_transform(self.get_spine_transform())
  288. if self.axis is not None:
  289. self.axis.reset_ticks()
  290. self.stale = True
  291. def get_position(self):
  292. """Return the spine position."""
  293. self._ensure_position_is_set()
  294. return self._position
  295. def get_spine_transform(self):
  296. """Return the spine transform."""
  297. self._ensure_position_is_set()
  298. position = self._position
  299. if isinstance(position, str):
  300. if position == 'center':
  301. position = ('axes', 0.5)
  302. elif position == 'zero':
  303. position = ('data', 0)
  304. assert len(position) == 2, 'position should be 2-tuple'
  305. position_type, amount = position
  306. _api.check_in_list(['axes', 'outward', 'data'],
  307. position_type=position_type)
  308. if self.spine_type in ['left', 'right']:
  309. base_transform = self.axes.get_yaxis_transform(which='grid')
  310. elif self.spine_type in ['top', 'bottom']:
  311. base_transform = self.axes.get_xaxis_transform(which='grid')
  312. else:
  313. raise ValueError(f'unknown spine spine_type: {self.spine_type!r}')
  314. if position_type == 'outward':
  315. if amount == 0: # short circuit commonest case
  316. return base_transform
  317. else:
  318. offset_vec = {'left': (-1, 0), 'right': (1, 0),
  319. 'bottom': (0, -1), 'top': (0, 1),
  320. }[self.spine_type]
  321. # calculate x and y offset in dots
  322. offset_dots = amount * np.array(offset_vec) / 72
  323. return (base_transform
  324. + mtransforms.ScaledTranslation(
  325. *offset_dots, self.get_figure(root=False).dpi_scale_trans))
  326. elif position_type == 'axes':
  327. if self.spine_type in ['left', 'right']:
  328. # keep y unchanged, fix x at amount
  329. return (mtransforms.Affine2D.from_values(0, 0, 0, 1, amount, 0)
  330. + base_transform)
  331. elif self.spine_type in ['bottom', 'top']:
  332. # keep x unchanged, fix y at amount
  333. return (mtransforms.Affine2D.from_values(1, 0, 0, 0, 0, amount)
  334. + base_transform)
  335. elif position_type == 'data':
  336. if self.spine_type in ('right', 'top'):
  337. # The right and top spines have a default position of 1 in
  338. # axes coordinates. When specifying the position in data
  339. # coordinates, we need to calculate the position relative to 0.
  340. amount -= 1
  341. if self.spine_type in ('left', 'right'):
  342. return mtransforms.blended_transform_factory(
  343. mtransforms.Affine2D().translate(amount, 0)
  344. + self.axes.transData,
  345. self.axes.transData)
  346. elif self.spine_type in ('bottom', 'top'):
  347. return mtransforms.blended_transform_factory(
  348. self.axes.transData,
  349. mtransforms.Affine2D().translate(0, amount)
  350. + self.axes.transData)
  351. def set_bounds(self, low=None, high=None):
  352. """
  353. Set the spine bounds.
  354. Parameters
  355. ----------
  356. low : float or None, optional
  357. The lower spine bound. Passing *None* leaves the limit unchanged.
  358. The bounds may also be passed as the tuple (*low*, *high*) as the
  359. first positional argument.
  360. .. ACCEPTS: (low: float, high: float)
  361. high : float or None, optional
  362. The higher spine bound. Passing *None* leaves the limit unchanged.
  363. """
  364. if self.spine_type == 'circle':
  365. raise ValueError(
  366. 'set_bounds() method incompatible with circular spines')
  367. if high is None and np.iterable(low):
  368. low, high = low
  369. old_low, old_high = self.get_bounds() or (None, None)
  370. if low is None:
  371. low = old_low
  372. if high is None:
  373. high = old_high
  374. self._bounds = (low, high)
  375. self.stale = True
  376. def get_bounds(self):
  377. """Get the bounds of the spine."""
  378. return self._bounds
  379. @classmethod
  380. def linear_spine(cls, axes, spine_type, **kwargs):
  381. """Create and return a linear `Spine`."""
  382. # all values of 0.999 get replaced upon call to set_bounds()
  383. if spine_type == 'left':
  384. path = mpath.Path([(0.0, 0.999), (0.0, 0.999)])
  385. elif spine_type == 'right':
  386. path = mpath.Path([(1.0, 0.999), (1.0, 0.999)])
  387. elif spine_type == 'bottom':
  388. path = mpath.Path([(0.999, 0.0), (0.999, 0.0)])
  389. elif spine_type == 'top':
  390. path = mpath.Path([(0.999, 1.0), (0.999, 1.0)])
  391. else:
  392. raise ValueError('unable to make path for spine "%s"' % spine_type)
  393. result = cls(axes, spine_type, path, **kwargs)
  394. result.set_visible(mpl.rcParams[f'axes.spines.{spine_type}'])
  395. return result
  396. @classmethod
  397. def arc_spine(cls, axes, spine_type, center, radius, theta1, theta2,
  398. **kwargs):
  399. """Create and return an arc `Spine`."""
  400. path = mpath.Path.arc(theta1, theta2)
  401. result = cls(axes, spine_type, path, **kwargs)
  402. result.set_patch_arc(center, radius, theta1, theta2)
  403. return result
  404. @classmethod
  405. def circular_spine(cls, axes, center, radius, **kwargs):
  406. """Create and return a circular `Spine`."""
  407. path = mpath.Path.unit_circle()
  408. spine_type = 'circle'
  409. result = cls(axes, spine_type, path, **kwargs)
  410. result.set_patch_circle(center, radius)
  411. return result
  412. def set_color(self, c):
  413. """
  414. Set the edgecolor.
  415. Parameters
  416. ----------
  417. c : :mpltype:`color`
  418. Notes
  419. -----
  420. This method does not modify the facecolor (which defaults to "none"),
  421. unlike the `.Patch.set_color` method defined in the parent class. Use
  422. `.Patch.set_facecolor` to set the facecolor.
  423. """
  424. self.set_edgecolor(c)
  425. self.stale = True
  426. class SpinesProxy:
  427. """
  428. A proxy to broadcast ``set_*()`` and ``set()`` method calls to contained `.Spines`.
  429. The proxy cannot be used for any other operations on its members.
  430. The supported methods are determined dynamically based on the contained
  431. spines. If not all spines support a given method, it's executed only on
  432. the subset of spines that support it.
  433. """
  434. def __init__(self, spine_dict):
  435. self._spine_dict = spine_dict
  436. def __getattr__(self, name):
  437. broadcast_targets = [spine for spine in self._spine_dict.values()
  438. if hasattr(spine, name)]
  439. if (name != 'set' and not name.startswith('set_')) or not broadcast_targets:
  440. raise AttributeError(
  441. f"'SpinesProxy' object has no attribute '{name}'")
  442. def x(_targets, _funcname, *args, **kwargs):
  443. for spine in _targets:
  444. getattr(spine, _funcname)(*args, **kwargs)
  445. x = functools.partial(x, broadcast_targets, name)
  446. x.__doc__ = broadcast_targets[0].__doc__
  447. return x
  448. def __dir__(self):
  449. names = []
  450. for spine in self._spine_dict.values():
  451. names.extend(name
  452. for name in dir(spine) if name.startswith('set_'))
  453. return list(sorted(set(names)))
  454. class Spines(MutableMapping):
  455. r"""
  456. The container of all `.Spine`\s in an Axes.
  457. The interface is dict-like mapping names (e.g. 'left') to `.Spine` objects.
  458. Additionally, it implements some pandas.Series-like features like accessing
  459. elements by attribute::
  460. spines['top'].set_visible(False)
  461. spines.top.set_visible(False)
  462. Multiple spines can be addressed simultaneously by passing a list::
  463. spines[['top', 'right']].set_visible(False)
  464. Use an open slice to address all spines::
  465. spines[:].set_visible(False)
  466. The latter two indexing methods will return a `SpinesProxy` that broadcasts all
  467. ``set_*()`` and ``set()`` calls to its members, but cannot be used for any other
  468. operation.
  469. """
  470. def __init__(self, **kwargs):
  471. self._dict = kwargs
  472. @classmethod
  473. def from_dict(cls, d):
  474. return cls(**d)
  475. def __getstate__(self):
  476. return self._dict
  477. def __setstate__(self, state):
  478. self.__init__(**state)
  479. def __getattr__(self, name):
  480. try:
  481. return self._dict[name]
  482. except KeyError:
  483. raise AttributeError(
  484. f"'Spines' object does not contain a '{name}' spine")
  485. def __getitem__(self, key):
  486. if isinstance(key, list):
  487. unknown_keys = [k for k in key if k not in self._dict]
  488. if unknown_keys:
  489. raise KeyError(', '.join(unknown_keys))
  490. return SpinesProxy({k: v for k, v in self._dict.items()
  491. if k in key})
  492. if isinstance(key, tuple):
  493. raise ValueError('Multiple spines must be passed as a single list')
  494. if isinstance(key, slice):
  495. if key.start is None and key.stop is None and key.step is None:
  496. return SpinesProxy(self._dict)
  497. else:
  498. raise ValueError(
  499. 'Spines does not support slicing except for the fully '
  500. 'open slice [:] to access all spines.')
  501. return self._dict[key]
  502. def __setitem__(self, key, value):
  503. # TODO: Do we want to deprecate adding spines?
  504. self._dict[key] = value
  505. def __delitem__(self, key):
  506. # TODO: Do we want to deprecate deleting spines?
  507. del self._dict[key]
  508. def __iter__(self):
  509. return iter(self._dict)
  510. def __len__(self):
  511. return len(self._dict)