spines.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  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.dedent_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.figure)
  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. padout = padout * tickl / 72 * self.figure.dpi
  153. padin = padin * tickl / 72 * self.figure.dpi
  154. if tick.tick1line.get_visible():
  155. if self.spine_type == 'left':
  156. bb0.x0 = bb0.x0 - padout
  157. bb0.x1 = bb0.x1 + padin
  158. elif self.spine_type == 'bottom':
  159. bb0.y0 = bb0.y0 - padout
  160. bb0.y1 = bb0.y1 + padin
  161. if tick.tick2line.get_visible():
  162. if self.spine_type == 'right':
  163. bb0.x1 = bb0.x1 + padout
  164. bb0.x0 = bb0.x0 - padin
  165. elif self.spine_type == 'top':
  166. bb0.y1 = bb0.y1 + padout
  167. bb0.y0 = bb0.y0 - padout
  168. bboxes.append(bb0)
  169. return mtransforms.Bbox.union(bboxes)
  170. def get_path(self):
  171. return self._path
  172. def _ensure_position_is_set(self):
  173. if self._position is None:
  174. # default position
  175. self._position = ('outward', 0.0) # in points
  176. self.set_position(self._position)
  177. def register_axis(self, axis):
  178. """
  179. Register an axis.
  180. An axis should be registered with its corresponding spine from
  181. the Axes instance. This allows the spine to clear any axis
  182. properties when needed.
  183. """
  184. self.axis = axis
  185. self.stale = True
  186. def clear(self):
  187. """Clear the current spine."""
  188. self._clear()
  189. if self.axis is not None:
  190. self.axis.clear()
  191. def _clear(self):
  192. """
  193. Clear things directly related to the spine.
  194. In this way it is possible to avoid clearing the Axis as well when calling
  195. from library code where it is known that the Axis is cleared separately.
  196. """
  197. self._position = None # clear position
  198. def _adjust_location(self):
  199. """Automatically set spine bounds to the view interval."""
  200. if self.spine_type == 'circle':
  201. return
  202. if self._bounds is not None:
  203. low, high = self._bounds
  204. elif self.spine_type in ('left', 'right'):
  205. low, high = self.axes.viewLim.intervaly
  206. elif self.spine_type in ('top', 'bottom'):
  207. low, high = self.axes.viewLim.intervalx
  208. else:
  209. raise ValueError(f'unknown spine spine_type: {self.spine_type}')
  210. if self._patch_type == 'arc':
  211. if self.spine_type in ('bottom', 'top'):
  212. try:
  213. direction = self.axes.get_theta_direction()
  214. except AttributeError:
  215. direction = 1
  216. try:
  217. offset = self.axes.get_theta_offset()
  218. except AttributeError:
  219. offset = 0
  220. low = low * direction + offset
  221. high = high * direction + offset
  222. if low > high:
  223. low, high = high, low
  224. self._path = mpath.Path.arc(np.rad2deg(low), np.rad2deg(high))
  225. if self.spine_type == 'bottom':
  226. rmin, rmax = self.axes.viewLim.intervaly
  227. try:
  228. rorigin = self.axes.get_rorigin()
  229. except AttributeError:
  230. rorigin = rmin
  231. scaled_diameter = (rmin - rorigin) / (rmax - rorigin)
  232. self._height = scaled_diameter
  233. self._width = scaled_diameter
  234. else:
  235. raise ValueError('unable to set bounds for spine "%s"' %
  236. self.spine_type)
  237. else:
  238. v1 = self._path.vertices
  239. assert v1.shape == (2, 2), 'unexpected vertices shape'
  240. if self.spine_type in ['left', 'right']:
  241. v1[0, 1] = low
  242. v1[1, 1] = high
  243. elif self.spine_type in ['bottom', 'top']:
  244. v1[0, 0] = low
  245. v1[1, 0] = high
  246. else:
  247. raise ValueError('unable to set bounds for spine "%s"' %
  248. self.spine_type)
  249. @allow_rasterization
  250. def draw(self, renderer):
  251. self._adjust_location()
  252. ret = super().draw(renderer)
  253. self.stale = False
  254. return ret
  255. def set_position(self, position):
  256. """
  257. Set the position of the spine.
  258. Spine position is specified by a 2 tuple of (position type,
  259. amount). The position types are:
  260. * 'outward': place the spine out from the data area by the specified
  261. number of points. (Negative values place the spine inwards.)
  262. * 'axes': place the spine at the specified Axes coordinate (0 to 1).
  263. * 'data': place the spine at the specified data coordinate.
  264. Additionally, shorthand notations define a special positions:
  265. * 'center' -> ``('axes', 0.5)``
  266. * 'zero' -> ``('data', 0.0)``
  267. Examples
  268. --------
  269. :doc:`/gallery/spines/spine_placement_demo`
  270. """
  271. if position in ('center', 'zero'): # special positions
  272. pass
  273. else:
  274. if len(position) != 2:
  275. raise ValueError("position should be 'center' or 2-tuple")
  276. if position[0] not in ['outward', 'axes', 'data']:
  277. raise ValueError("position[0] should be one of 'outward', "
  278. "'axes', or 'data' ")
  279. self._position = position
  280. self.set_transform(self.get_spine_transform())
  281. if self.axis is not None:
  282. self.axis.reset_ticks()
  283. self.stale = True
  284. def get_position(self):
  285. """Return the spine position."""
  286. self._ensure_position_is_set()
  287. return self._position
  288. def get_spine_transform(self):
  289. """Return the spine transform."""
  290. self._ensure_position_is_set()
  291. position = self._position
  292. if isinstance(position, str):
  293. if position == 'center':
  294. position = ('axes', 0.5)
  295. elif position == 'zero':
  296. position = ('data', 0)
  297. assert len(position) == 2, 'position should be 2-tuple'
  298. position_type, amount = position
  299. _api.check_in_list(['axes', 'outward', 'data'],
  300. position_type=position_type)
  301. if self.spine_type in ['left', 'right']:
  302. base_transform = self.axes.get_yaxis_transform(which='grid')
  303. elif self.spine_type in ['top', 'bottom']:
  304. base_transform = self.axes.get_xaxis_transform(which='grid')
  305. else:
  306. raise ValueError(f'unknown spine spine_type: {self.spine_type!r}')
  307. if position_type == 'outward':
  308. if amount == 0: # short circuit commonest case
  309. return base_transform
  310. else:
  311. offset_vec = {'left': (-1, 0), 'right': (1, 0),
  312. 'bottom': (0, -1), 'top': (0, 1),
  313. }[self.spine_type]
  314. # calculate x and y offset in dots
  315. offset_dots = amount * np.array(offset_vec) / 72
  316. return (base_transform
  317. + mtransforms.ScaledTranslation(
  318. *offset_dots, self.figure.dpi_scale_trans))
  319. elif position_type == 'axes':
  320. if self.spine_type in ['left', 'right']:
  321. # keep y unchanged, fix x at amount
  322. return (mtransforms.Affine2D.from_values(0, 0, 0, 1, amount, 0)
  323. + base_transform)
  324. elif self.spine_type in ['bottom', 'top']:
  325. # keep x unchanged, fix y at amount
  326. return (mtransforms.Affine2D.from_values(1, 0, 0, 0, 0, amount)
  327. + base_transform)
  328. elif position_type == 'data':
  329. if self.spine_type in ('right', 'top'):
  330. # The right and top spines have a default position of 1 in
  331. # axes coordinates. When specifying the position in data
  332. # coordinates, we need to calculate the position relative to 0.
  333. amount -= 1
  334. if self.spine_type in ('left', 'right'):
  335. return mtransforms.blended_transform_factory(
  336. mtransforms.Affine2D().translate(amount, 0)
  337. + self.axes.transData,
  338. self.axes.transData)
  339. elif self.spine_type in ('bottom', 'top'):
  340. return mtransforms.blended_transform_factory(
  341. self.axes.transData,
  342. mtransforms.Affine2D().translate(0, amount)
  343. + self.axes.transData)
  344. def set_bounds(self, low=None, high=None):
  345. """
  346. Set the spine bounds.
  347. Parameters
  348. ----------
  349. low : float or None, optional
  350. The lower spine bound. Passing *None* leaves the limit unchanged.
  351. The bounds may also be passed as the tuple (*low*, *high*) as the
  352. first positional argument.
  353. .. ACCEPTS: (low: float, high: float)
  354. high : float or None, optional
  355. The higher spine bound. Passing *None* leaves the limit unchanged.
  356. """
  357. if self.spine_type == 'circle':
  358. raise ValueError(
  359. 'set_bounds() method incompatible with circular spines')
  360. if high is None and np.iterable(low):
  361. low, high = low
  362. old_low, old_high = self.get_bounds() or (None, None)
  363. if low is None:
  364. low = old_low
  365. if high is None:
  366. high = old_high
  367. self._bounds = (low, high)
  368. self.stale = True
  369. def get_bounds(self):
  370. """Get the bounds of the spine."""
  371. return self._bounds
  372. @classmethod
  373. def linear_spine(cls, axes, spine_type, **kwargs):
  374. """Create and return a linear `Spine`."""
  375. # all values of 0.999 get replaced upon call to set_bounds()
  376. if spine_type == 'left':
  377. path = mpath.Path([(0.0, 0.999), (0.0, 0.999)])
  378. elif spine_type == 'right':
  379. path = mpath.Path([(1.0, 0.999), (1.0, 0.999)])
  380. elif spine_type == 'bottom':
  381. path = mpath.Path([(0.999, 0.0), (0.999, 0.0)])
  382. elif spine_type == 'top':
  383. path = mpath.Path([(0.999, 1.0), (0.999, 1.0)])
  384. else:
  385. raise ValueError('unable to make path for spine "%s"' % spine_type)
  386. result = cls(axes, spine_type, path, **kwargs)
  387. result.set_visible(mpl.rcParams[f'axes.spines.{spine_type}'])
  388. return result
  389. @classmethod
  390. def arc_spine(cls, axes, spine_type, center, radius, theta1, theta2,
  391. **kwargs):
  392. """Create and return an arc `Spine`."""
  393. path = mpath.Path.arc(theta1, theta2)
  394. result = cls(axes, spine_type, path, **kwargs)
  395. result.set_patch_arc(center, radius, theta1, theta2)
  396. return result
  397. @classmethod
  398. def circular_spine(cls, axes, center, radius, **kwargs):
  399. """Create and return a circular `Spine`."""
  400. path = mpath.Path.unit_circle()
  401. spine_type = 'circle'
  402. result = cls(axes, spine_type, path, **kwargs)
  403. result.set_patch_circle(center, radius)
  404. return result
  405. def set_color(self, c):
  406. """
  407. Set the edgecolor.
  408. Parameters
  409. ----------
  410. c : color
  411. Notes
  412. -----
  413. This method does not modify the facecolor (which defaults to "none"),
  414. unlike the `.Patch.set_color` method defined in the parent class. Use
  415. `.Patch.set_facecolor` to set the facecolor.
  416. """
  417. self.set_edgecolor(c)
  418. self.stale = True
  419. class SpinesProxy:
  420. """
  421. A proxy to broadcast ``set_*()`` and ``set()`` method calls to contained `.Spines`.
  422. The proxy cannot be used for any other operations on its members.
  423. The supported methods are determined dynamically based on the contained
  424. spines. If not all spines support a given method, it's executed only on
  425. the subset of spines that support it.
  426. """
  427. def __init__(self, spine_dict):
  428. self._spine_dict = spine_dict
  429. def __getattr__(self, name):
  430. broadcast_targets = [spine for spine in self._spine_dict.values()
  431. if hasattr(spine, name)]
  432. if (name != 'set' and not name.startswith('set_')) or not broadcast_targets:
  433. raise AttributeError(
  434. f"'SpinesProxy' object has no attribute '{name}'")
  435. def x(_targets, _funcname, *args, **kwargs):
  436. for spine in _targets:
  437. getattr(spine, _funcname)(*args, **kwargs)
  438. x = functools.partial(x, broadcast_targets, name)
  439. x.__doc__ = broadcast_targets[0].__doc__
  440. return x
  441. def __dir__(self):
  442. names = []
  443. for spine in self._spine_dict.values():
  444. names.extend(name
  445. for name in dir(spine) if name.startswith('set_'))
  446. return list(sorted(set(names)))
  447. class Spines(MutableMapping):
  448. r"""
  449. The container of all `.Spine`\s in an Axes.
  450. The interface is dict-like mapping names (e.g. 'left') to `.Spine` objects.
  451. Additionally, it implements some pandas.Series-like features like accessing
  452. elements by attribute::
  453. spines['top'].set_visible(False)
  454. spines.top.set_visible(False)
  455. Multiple spines can be addressed simultaneously by passing a list::
  456. spines[['top', 'right']].set_visible(False)
  457. Use an open slice to address all spines::
  458. spines[:].set_visible(False)
  459. The latter two indexing methods will return a `SpinesProxy` that broadcasts all
  460. ``set_*()`` and ``set()`` calls to its members, but cannot be used for any other
  461. operation.
  462. """
  463. def __init__(self, **kwargs):
  464. self._dict = kwargs
  465. @classmethod
  466. def from_dict(cls, d):
  467. return cls(**d)
  468. def __getstate__(self):
  469. return self._dict
  470. def __setstate__(self, state):
  471. self.__init__(**state)
  472. def __getattr__(self, name):
  473. try:
  474. return self._dict[name]
  475. except KeyError:
  476. raise AttributeError(
  477. f"'Spines' object does not contain a '{name}' spine")
  478. def __getitem__(self, key):
  479. if isinstance(key, list):
  480. unknown_keys = [k for k in key if k not in self._dict]
  481. if unknown_keys:
  482. raise KeyError(', '.join(unknown_keys))
  483. return SpinesProxy({k: v for k, v in self._dict.items()
  484. if k in key})
  485. if isinstance(key, tuple):
  486. raise ValueError('Multiple spines must be passed as a single list')
  487. if isinstance(key, slice):
  488. if key.start is None and key.stop is None and key.step is None:
  489. return SpinesProxy(self._dict)
  490. else:
  491. raise ValueError(
  492. 'Spines does not support slicing except for the fully '
  493. 'open slice [:] to access all spines.')
  494. return self._dict[key]
  495. def __setitem__(self, key, value):
  496. # TODO: Do we want to deprecate adding spines?
  497. self._dict[key] = value
  498. def __delitem__(self, key):
  499. # TODO: Do we want to deprecate deleting spines?
  500. del self._dict[key]
  501. def __iter__(self):
  502. return iter(self._dict)
  503. def __len__(self):
  504. return len(self._dict)