parasite_axes.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. from matplotlib import _api, cbook
  2. import matplotlib.artist as martist
  3. import matplotlib.transforms as mtransforms
  4. from matplotlib.transforms import Bbox
  5. from .mpl_axes import Axes
  6. class ParasiteAxesBase:
  7. def __init__(self, parent_axes, aux_transform=None,
  8. *, viewlim_mode=None, **kwargs):
  9. self._parent_axes = parent_axes
  10. self.transAux = aux_transform
  11. self.set_viewlim_mode(viewlim_mode)
  12. kwargs["frameon"] = False
  13. super().__init__(parent_axes.get_figure(root=False),
  14. parent_axes._position, **kwargs)
  15. def clear(self):
  16. super().clear()
  17. martist.setp(self.get_children(), visible=False)
  18. self._get_lines = self._parent_axes._get_lines
  19. self._parent_axes.callbacks._connect_picklable(
  20. "xlim_changed", self._sync_lims)
  21. self._parent_axes.callbacks._connect_picklable(
  22. "ylim_changed", self._sync_lims)
  23. def pick(self, mouseevent):
  24. # This most likely goes to Artist.pick (depending on axes_class given
  25. # to the factory), which only handles pick events registered on the
  26. # axes associated with each child:
  27. super().pick(mouseevent)
  28. # But parasite axes are additionally given pick events from their host
  29. # axes (cf. HostAxesBase.pick), which we handle here:
  30. for a in self.get_children():
  31. if (hasattr(mouseevent.inaxes, "parasites")
  32. and self in mouseevent.inaxes.parasites):
  33. a.pick(mouseevent)
  34. # aux_transform support
  35. def _set_lim_and_transforms(self):
  36. if self.transAux is not None:
  37. self.transAxes = self._parent_axes.transAxes
  38. self.transData = self.transAux + self._parent_axes.transData
  39. self._xaxis_transform = mtransforms.blended_transform_factory(
  40. self.transData, self.transAxes)
  41. self._yaxis_transform = mtransforms.blended_transform_factory(
  42. self.transAxes, self.transData)
  43. else:
  44. super()._set_lim_and_transforms()
  45. def set_viewlim_mode(self, mode):
  46. _api.check_in_list([None, "equal", "transform"], mode=mode)
  47. self._viewlim_mode = mode
  48. def get_viewlim_mode(self):
  49. return self._viewlim_mode
  50. def _sync_lims(self, parent):
  51. viewlim = parent.viewLim.frozen()
  52. mode = self.get_viewlim_mode()
  53. if mode is None:
  54. pass
  55. elif mode == "equal":
  56. self.viewLim.set(viewlim)
  57. elif mode == "transform":
  58. self.viewLim.set(viewlim.transformed(self.transAux.inverted()))
  59. else:
  60. _api.check_in_list([None, "equal", "transform"], mode=mode)
  61. # end of aux_transform support
  62. parasite_axes_class_factory = cbook._make_class_factory(
  63. ParasiteAxesBase, "{}Parasite")
  64. ParasiteAxes = parasite_axes_class_factory(Axes)
  65. class HostAxesBase:
  66. def __init__(self, *args, **kwargs):
  67. self.parasites = []
  68. super().__init__(*args, **kwargs)
  69. def get_aux_axes(
  70. self, tr=None, viewlim_mode="equal", axes_class=None, **kwargs):
  71. """
  72. Add a parasite axes to this host.
  73. Despite this method's name, this should actually be thought of as an
  74. ``add_parasite_axes`` method.
  75. .. versionchanged:: 3.7
  76. Defaults to same base axes class as host axes.
  77. Parameters
  78. ----------
  79. tr : `~matplotlib.transforms.Transform` or None, default: None
  80. If a `.Transform`, the following relation will hold:
  81. ``parasite.transData = tr + host.transData``.
  82. If None, the parasite's and the host's ``transData`` are unrelated.
  83. viewlim_mode : {"equal", "transform", None}, default: "equal"
  84. How the parasite's view limits are set: directly equal to the
  85. parent axes ("equal"), equal after application of *tr*
  86. ("transform"), or independently (None).
  87. axes_class : subclass type of `~matplotlib.axes.Axes`, optional
  88. The `~.axes.Axes` subclass that is instantiated. If None, the base
  89. class of the host axes is used.
  90. **kwargs
  91. Other parameters are forwarded to the parasite axes constructor.
  92. """
  93. if axes_class is None:
  94. axes_class = self._base_axes_class
  95. parasite_axes_class = parasite_axes_class_factory(axes_class)
  96. ax2 = parasite_axes_class(
  97. self, tr, viewlim_mode=viewlim_mode, **kwargs)
  98. # note that ax2.transData == tr + ax1.transData
  99. # Anything you draw in ax2 will match the ticks and grids of ax1.
  100. self.parasites.append(ax2)
  101. ax2._remove_method = self.parasites.remove
  102. return ax2
  103. def draw(self, renderer):
  104. orig_children_len = len(self._children)
  105. locator = self.get_axes_locator()
  106. if locator:
  107. pos = locator(self, renderer)
  108. self.set_position(pos, which="active")
  109. self.apply_aspect(pos)
  110. else:
  111. self.apply_aspect()
  112. rect = self.get_position()
  113. for ax in self.parasites:
  114. ax.apply_aspect(rect)
  115. self._children.extend(ax.get_children())
  116. super().draw(renderer)
  117. del self._children[orig_children_len:]
  118. def clear(self):
  119. super().clear()
  120. for ax in self.parasites:
  121. ax.clear()
  122. def pick(self, mouseevent):
  123. super().pick(mouseevent)
  124. # Also pass pick events on to parasite axes and, in turn, their
  125. # children (cf. ParasiteAxesBase.pick)
  126. for a in self.parasites:
  127. a.pick(mouseevent)
  128. def twinx(self, axes_class=None):
  129. """
  130. Create a twin of Axes with a shared x-axis but independent y-axis.
  131. The y-axis of self will have ticks on the left and the returned axes
  132. will have ticks on the right.
  133. """
  134. ax = self._add_twin_axes(axes_class, sharex=self)
  135. self.axis["right"].set_visible(False)
  136. ax.axis["right"].set_visible(True)
  137. ax.axis["left", "top", "bottom"].set_visible(False)
  138. return ax
  139. def twiny(self, axes_class=None):
  140. """
  141. Create a twin of Axes with a shared y-axis but independent x-axis.
  142. The x-axis of self will have ticks on the bottom and the returned axes
  143. will have ticks on the top.
  144. """
  145. ax = self._add_twin_axes(axes_class, sharey=self)
  146. self.axis["top"].set_visible(False)
  147. ax.axis["top"].set_visible(True)
  148. ax.axis["left", "right", "bottom"].set_visible(False)
  149. return ax
  150. def twin(self, aux_trans=None, axes_class=None):
  151. """
  152. Create a twin of Axes with no shared axis.
  153. While self will have ticks on the left and bottom axis, the returned
  154. axes will have ticks on the top and right axis.
  155. """
  156. if aux_trans is None:
  157. aux_trans = mtransforms.IdentityTransform()
  158. ax = self._add_twin_axes(
  159. axes_class, aux_transform=aux_trans, viewlim_mode="transform")
  160. self.axis["top", "right"].set_visible(False)
  161. ax.axis["top", "right"].set_visible(True)
  162. ax.axis["left", "bottom"].set_visible(False)
  163. return ax
  164. def _add_twin_axes(self, axes_class, **kwargs):
  165. """
  166. Helper for `.twinx`/`.twiny`/`.twin`.
  167. *kwargs* are forwarded to the parasite axes constructor.
  168. """
  169. if axes_class is None:
  170. axes_class = self._base_axes_class
  171. ax = parasite_axes_class_factory(axes_class)(self, **kwargs)
  172. self.parasites.append(ax)
  173. ax._remove_method = self._remove_any_twin
  174. return ax
  175. def _remove_any_twin(self, ax):
  176. self.parasites.remove(ax)
  177. restore = ["top", "right"]
  178. if ax._sharex:
  179. restore.remove("top")
  180. if ax._sharey:
  181. restore.remove("right")
  182. self.axis[tuple(restore)].set_visible(True)
  183. self.axis[tuple(restore)].toggle(ticklabels=False, label=False)
  184. def get_tightbbox(self, renderer=None, *, call_axes_locator=True,
  185. bbox_extra_artists=None):
  186. bbs = [
  187. *[ax.get_tightbbox(renderer, call_axes_locator=call_axes_locator)
  188. for ax in self.parasites],
  189. super().get_tightbbox(renderer,
  190. call_axes_locator=call_axes_locator,
  191. bbox_extra_artists=bbox_extra_artists)]
  192. return Bbox.union([b for b in bbs if b.width != 0 or b.height != 0])
  193. host_axes_class_factory = host_subplot_class_factory = \
  194. cbook._make_class_factory(HostAxesBase, "{}HostAxes", "_base_axes_class")
  195. HostAxes = SubplotHost = host_axes_class_factory(Axes)
  196. def host_axes(*args, axes_class=Axes, figure=None, **kwargs):
  197. """
  198. Create axes that can act as a hosts to parasitic axes.
  199. Parameters
  200. ----------
  201. figure : `~matplotlib.figure.Figure`
  202. Figure to which the axes will be added. Defaults to the current figure
  203. `.pyplot.gcf()`.
  204. *args, **kwargs
  205. Will be passed on to the underlying `~.axes.Axes` object creation.
  206. """
  207. import matplotlib.pyplot as plt
  208. host_axes_class = host_axes_class_factory(axes_class)
  209. if figure is None:
  210. figure = plt.gcf()
  211. ax = host_axes_class(figure, *args, **kwargs)
  212. figure.add_axes(ax)
  213. return ax
  214. host_subplot = host_axes