axislines.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. """
  2. Axislines includes modified implementation of the Axes class. The
  3. biggest difference is that the artists responsible for drawing the axis spine,
  4. ticks, ticklabels and axis labels are separated out from Matplotlib's Axis
  5. class. Originally, this change was motivated to support curvilinear
  6. grid. Here are a few reasons that I came up with a new axes class:
  7. * "top" and "bottom" x-axis (or "left" and "right" y-axis) can have
  8. different ticks (tick locations and labels). This is not possible
  9. with the current Matplotlib, although some twin axes trick can help.
  10. * Curvilinear grid.
  11. * angled ticks.
  12. In the new axes class, xaxis and yaxis is set to not visible by
  13. default, and new set of artist (AxisArtist) are defined to draw axis
  14. line, ticks, ticklabels and axis label. Axes.axis attribute serves as
  15. a dictionary of these artists, i.e., ax.axis["left"] is a AxisArtist
  16. instance responsible to draw left y-axis. The default Axes.axis contains
  17. "bottom", "left", "top" and "right".
  18. AxisArtist can be considered as a container artist and
  19. has following children artists which will draw ticks, labels, etc.
  20. * line
  21. * major_ticks, major_ticklabels
  22. * minor_ticks, minor_ticklabels
  23. * offsetText
  24. * label
  25. Note that these are separate artists from `matplotlib.axis.Axis`, thus most
  26. tick-related functions in Matplotlib won't work. For example, color and
  27. markerwidth of the ``ax.axis["bottom"].major_ticks`` will follow those of
  28. Axes.xaxis unless explicitly specified.
  29. In addition to AxisArtist, the Axes will have *gridlines* attribute,
  30. which obviously draws grid lines. The gridlines needs to be separated
  31. from the axis as some gridlines can never pass any axis.
  32. """
  33. import numpy as np
  34. from matplotlib import cbook, rcParams
  35. import matplotlib.axes as maxes
  36. from matplotlib.path import Path
  37. from mpl_toolkits.axes_grid1 import mpl_axes
  38. from .axisline_style import AxislineStyle
  39. from .axis_artist import AxisArtist, GridlinesCollection
  40. class AxisArtistHelper:
  41. """
  42. AxisArtistHelper should define
  43. following method with given APIs. Note that the first axes argument
  44. will be axes attribute of the caller artist.::
  45. # LINE (spinal line?)
  46. def get_line(self, axes):
  47. # path : Path
  48. return path
  49. def get_line_transform(self, axes):
  50. # ...
  51. # trans : transform
  52. return trans
  53. # LABEL
  54. def get_label_pos(self, axes):
  55. # x, y : position
  56. return (x, y), trans
  57. def get_label_offset_transform(self,
  58. axes,
  59. pad_points, fontprops, renderer,
  60. bboxes,
  61. ):
  62. # va : vertical alignment
  63. # ha : horizontal alignment
  64. # a : angle
  65. return trans, va, ha, a
  66. # TICK
  67. def get_tick_transform(self, axes):
  68. return trans
  69. def get_tick_iterators(self, axes):
  70. # iter : iterable object that yields (c, angle, l) where
  71. # c, angle, l is position, tick angle, and label
  72. return iter_major, iter_minor
  73. """
  74. class _Base:
  75. """Base class for axis helper."""
  76. def __init__(self):
  77. self.delta1, self.delta2 = 0.00001, 0.00001
  78. def update_lim(self, axes):
  79. pass
  80. class Fixed(_Base):
  81. """Helper class for a fixed (in the axes coordinate) axis."""
  82. _default_passthru_pt = dict(left=(0, 0),
  83. right=(1, 0),
  84. bottom=(0, 0),
  85. top=(0, 1))
  86. def __init__(self, loc, nth_coord=None):
  87. """
  88. nth_coord = along which coordinate value varies
  89. in 2d, nth_coord = 0 -> x axis, nth_coord = 1 -> y axis
  90. """
  91. cbook._check_in_list(["left", "right", "bottom", "top"], loc=loc)
  92. self._loc = loc
  93. if nth_coord is None:
  94. if loc in ["left", "right"]:
  95. nth_coord = 1
  96. elif loc in ["bottom", "top"]:
  97. nth_coord = 0
  98. self.nth_coord = nth_coord
  99. super().__init__()
  100. self.passthru_pt = self._default_passthru_pt[loc]
  101. _verts = np.array([[0., 0.],
  102. [1., 1.]])
  103. fixed_coord = 1 - nth_coord
  104. _verts[:, fixed_coord] = self.passthru_pt[fixed_coord]
  105. # axis line in transAxes
  106. self._path = Path(_verts)
  107. def get_nth_coord(self):
  108. return self.nth_coord
  109. # LINE
  110. def get_line(self, axes):
  111. return self._path
  112. def get_line_transform(self, axes):
  113. return axes.transAxes
  114. # LABEL
  115. def get_axislabel_transform(self, axes):
  116. return axes.transAxes
  117. def get_axislabel_pos_angle(self, axes):
  118. """
  119. Return the label reference position in transAxes.
  120. get_label_transform() returns a transform of (transAxes+offset)
  121. """
  122. return dict(left=((0., 0.5), 90), # (position, angle_tangent)
  123. right=((1., 0.5), 90),
  124. bottom=((0.5, 0.), 0),
  125. top=((0.5, 1.), 0))[self._loc]
  126. # TICK
  127. def get_tick_transform(self, axes):
  128. return [axes.get_xaxis_transform(),
  129. axes.get_yaxis_transform()][self.nth_coord]
  130. class Floating(_Base):
  131. def __init__(self, nth_coord, value):
  132. self.nth_coord = nth_coord
  133. self._value = value
  134. super().__init__()
  135. def get_nth_coord(self):
  136. return self.nth_coord
  137. def get_line(self, axes):
  138. raise RuntimeError(
  139. "get_line method should be defined by the derived class")
  140. class AxisArtistHelperRectlinear:
  141. class Fixed(AxisArtistHelper.Fixed):
  142. def __init__(self, axes, loc, nth_coord=None):
  143. """
  144. nth_coord = along which coordinate value varies
  145. in 2d, nth_coord = 0 -> x axis, nth_coord = 1 -> y axis
  146. """
  147. super().__init__(loc, nth_coord)
  148. self.axis = [axes.xaxis, axes.yaxis][self.nth_coord]
  149. # TICK
  150. def get_tick_iterators(self, axes):
  151. """tick_loc, tick_angle, tick_label"""
  152. loc = self._loc
  153. if loc in ["bottom", "top"]:
  154. angle_normal, angle_tangent = 90, 0
  155. else:
  156. angle_normal, angle_tangent = 0, 90
  157. major = self.axis.major
  158. majorLocs = major.locator()
  159. majorLabels = major.formatter.format_ticks(majorLocs)
  160. minor = self.axis.minor
  161. minorLocs = minor.locator()
  162. minorLabels = minor.formatter.format_ticks(minorLocs)
  163. tick_to_axes = self.get_tick_transform(axes) - axes.transAxes
  164. def _f(locs, labels):
  165. for x, l in zip(locs, labels):
  166. c = list(self.passthru_pt) # copy
  167. c[self.nth_coord] = x
  168. # check if the tick point is inside axes
  169. c2 = tick_to_axes.transform(c)
  170. if (0 - self.delta1
  171. <= c2[self.nth_coord]
  172. <= 1 + self.delta2):
  173. yield c, angle_normal, angle_tangent, l
  174. return _f(majorLocs, majorLabels), _f(minorLocs, minorLabels)
  175. class Floating(AxisArtistHelper.Floating):
  176. def __init__(self, axes, nth_coord,
  177. passingthrough_point, axis_direction="bottom"):
  178. super().__init__(nth_coord, passingthrough_point)
  179. self._axis_direction = axis_direction
  180. self.axis = [axes.xaxis, axes.yaxis][self.nth_coord]
  181. def get_line(self, axes):
  182. _verts = np.array([[0., 0.],
  183. [1., 1.]])
  184. fixed_coord = 1 - self.nth_coord
  185. data_to_axes = axes.transData - axes.transAxes
  186. p = data_to_axes.transform([self._value, self._value])
  187. _verts[:, fixed_coord] = p[fixed_coord]
  188. return Path(_verts)
  189. def get_line_transform(self, axes):
  190. return axes.transAxes
  191. def get_axislabel_transform(self, axes):
  192. return axes.transAxes
  193. def get_axislabel_pos_angle(self, axes):
  194. """
  195. Return the label reference position in transAxes.
  196. get_label_transform() returns a transform of (transAxes+offset)
  197. """
  198. angle = [0, 90][self.nth_coord]
  199. _verts = [0.5, 0.5]
  200. fixed_coord = 1 - self.nth_coord
  201. data_to_axes = axes.transData - axes.transAxes
  202. p = data_to_axes.transform([self._value, self._value])
  203. _verts[fixed_coord] = p[fixed_coord]
  204. if 0 <= _verts[fixed_coord] <= 1:
  205. return _verts, angle
  206. else:
  207. return None, None
  208. def get_tick_transform(self, axes):
  209. return axes.transData
  210. def get_tick_iterators(self, axes):
  211. """tick_loc, tick_angle, tick_label"""
  212. if self.nth_coord == 0:
  213. angle_normal, angle_tangent = 90, 0
  214. else:
  215. angle_normal, angle_tangent = 0, 90
  216. major = self.axis.major
  217. majorLocs = major.locator()
  218. majorLabels = major.formatter.format_ticks(majorLocs)
  219. minor = self.axis.minor
  220. minorLocs = minor.locator()
  221. minorLabels = minor.formatter.format_ticks(minorLocs)
  222. data_to_axes = axes.transData - axes.transAxes
  223. def _f(locs, labels):
  224. for x, l in zip(locs, labels):
  225. c = [self._value, self._value]
  226. c[self.nth_coord] = x
  227. c1, c2 = data_to_axes.transform(c)
  228. if (0 <= c1 <= 1 and 0 <= c2 <= 1
  229. and 0 - self.delta1
  230. <= [c1, c2][self.nth_coord]
  231. <= 1 + self.delta2):
  232. yield c, angle_normal, angle_tangent, l
  233. return _f(majorLocs, majorLabels), _f(minorLocs, minorLabels)
  234. class GridHelperBase:
  235. def __init__(self):
  236. self._force_update = True
  237. self._old_limits = None
  238. super().__init__()
  239. def update_lim(self, axes):
  240. x1, x2 = axes.get_xlim()
  241. y1, y2 = axes.get_ylim()
  242. if self._force_update or self._old_limits != (x1, x2, y1, y2):
  243. self._update(x1, x2, y1, y2)
  244. self._force_update = False
  245. self._old_limits = (x1, x2, y1, y2)
  246. def _update(self, x1, x2, y1, y2):
  247. pass
  248. def invalidate(self):
  249. self._force_update = True
  250. def valid(self):
  251. return not self._force_update
  252. def get_gridlines(self, which, axis):
  253. """
  254. Return list of grid lines as a list of paths (list of points).
  255. *which* : "major" or "minor"
  256. *axis* : "both", "x" or "y"
  257. """
  258. return []
  259. def new_gridlines(self, ax):
  260. """
  261. Create and return a new GridlineCollection instance.
  262. *which* : "major" or "minor"
  263. *axis* : "both", "x" or "y"
  264. """
  265. gridlines = GridlinesCollection(None, transform=ax.transData,
  266. colors=rcParams['grid.color'],
  267. linestyles=rcParams['grid.linestyle'],
  268. linewidths=rcParams['grid.linewidth'])
  269. ax._set_artist_props(gridlines)
  270. gridlines.set_grid_helper(self)
  271. ax.axes._set_artist_props(gridlines)
  272. # gridlines.set_clip_path(self.axes.patch)
  273. # set_clip_path need to be deferred after Axes.cla is completed.
  274. # It is done inside the cla.
  275. return gridlines
  276. class GridHelperRectlinear(GridHelperBase):
  277. def __init__(self, axes):
  278. super().__init__()
  279. self.axes = axes
  280. def new_fixed_axis(self, loc,
  281. nth_coord=None,
  282. axis_direction=None,
  283. offset=None,
  284. axes=None,
  285. ):
  286. if axes is None:
  287. cbook._warn_external(
  288. "'new_fixed_axis' explicitly requires the axes keyword.")
  289. axes = self.axes
  290. _helper = AxisArtistHelperRectlinear.Fixed(axes, loc, nth_coord)
  291. if axis_direction is None:
  292. axis_direction = loc
  293. axisline = AxisArtist(axes, _helper, offset=offset,
  294. axis_direction=axis_direction,
  295. )
  296. return axisline
  297. def new_floating_axis(self, nth_coord, value,
  298. axis_direction="bottom",
  299. axes=None,
  300. ):
  301. if axes is None:
  302. cbook._warn_external(
  303. "'new_floating_axis' explicitly requires the axes keyword.")
  304. axes = self.axes
  305. _helper = AxisArtistHelperRectlinear.Floating(
  306. axes, nth_coord, value, axis_direction)
  307. axisline = AxisArtist(axes, _helper)
  308. axisline.line.set_clip_on(True)
  309. axisline.line.set_clip_box(axisline.axes.bbox)
  310. return axisline
  311. def get_gridlines(self, which="major", axis="both"):
  312. """
  313. Return list of gridline coordinates in data coordinates.
  314. *which* : "major" or "minor"
  315. *axis* : "both", "x" or "y"
  316. """
  317. gridlines = []
  318. if axis in ["both", "x"]:
  319. locs = []
  320. y1, y2 = self.axes.get_ylim()
  321. if which in ["both", "major"]:
  322. locs.extend(self.axes.xaxis.major.locator())
  323. if which in ["both", "minor"]:
  324. locs.extend(self.axes.xaxis.minor.locator())
  325. for x in locs:
  326. gridlines.append([[x, x], [y1, y2]])
  327. if axis in ["both", "y"]:
  328. x1, x2 = self.axes.get_xlim()
  329. locs = []
  330. if self.axes.yaxis._major_tick_kw["gridOn"]:
  331. locs.extend(self.axes.yaxis.major.locator())
  332. if self.axes.yaxis._minor_tick_kw["gridOn"]:
  333. locs.extend(self.axes.yaxis.minor.locator())
  334. for y in locs:
  335. gridlines.append([[x1, x2], [y, y]])
  336. return gridlines
  337. class Axes(maxes.Axes):
  338. def __call__(self, *args, **kwargs):
  339. return maxes.Axes.axis(self.axes, *args, **kwargs)
  340. def __init__(self, *args, grid_helper=None, **kwargs):
  341. self._axisline_on = True
  342. self._grid_helper = (grid_helper if grid_helper
  343. else GridHelperRectlinear(self))
  344. super().__init__(*args, **kwargs)
  345. self.toggle_axisline(True)
  346. def toggle_axisline(self, b=None):
  347. if b is None:
  348. b = not self._axisline_on
  349. if b:
  350. self._axisline_on = True
  351. for s in self.spines.values():
  352. s.set_visible(False)
  353. self.xaxis.set_visible(False)
  354. self.yaxis.set_visible(False)
  355. else:
  356. self._axisline_on = False
  357. for s in self.spines.values():
  358. s.set_visible(True)
  359. self.xaxis.set_visible(True)
  360. self.yaxis.set_visible(True)
  361. def _init_axis_artists(self, axes=None):
  362. if axes is None:
  363. axes = self
  364. self._axislines = mpl_axes.Axes.AxisDict(self)
  365. new_fixed_axis = self.get_grid_helper().new_fixed_axis
  366. for loc in ["bottom", "top", "left", "right"]:
  367. self._axislines[loc] = new_fixed_axis(loc=loc, axes=axes,
  368. axis_direction=loc)
  369. for axisline in [self._axislines["top"], self._axislines["right"]]:
  370. axisline.label.set_visible(False)
  371. axisline.major_ticklabels.set_visible(False)
  372. axisline.minor_ticklabels.set_visible(False)
  373. @property
  374. def axis(self):
  375. return self._axislines
  376. def new_gridlines(self, grid_helper=None):
  377. """
  378. Create and return a new GridlineCollection instance.
  379. *which* : "major" or "minor"
  380. *axis* : "both", "x" or "y"
  381. """
  382. if grid_helper is None:
  383. grid_helper = self.get_grid_helper()
  384. gridlines = grid_helper.new_gridlines(self)
  385. return gridlines
  386. def _init_gridlines(self, grid_helper=None):
  387. # It is done inside the cla.
  388. self.gridlines = self.new_gridlines(grid_helper)
  389. def cla(self):
  390. # gridlines need to b created before cla() since cla calls grid()
  391. self._init_gridlines()
  392. super().cla()
  393. # the clip_path should be set after Axes.cla() since that's
  394. # when a patch is created.
  395. self.gridlines.set_clip_path(self.axes.patch)
  396. self._init_axis_artists()
  397. def get_grid_helper(self):
  398. return self._grid_helper
  399. def grid(self, b=None, which='major', axis="both", **kwargs):
  400. """
  401. Toggle the gridlines, and optionally set the properties of the lines.
  402. """
  403. # There are some discrepancies in the behavior of grid() between
  404. # axes_grid and Matplotlib, because axes_grid explicitly sets the
  405. # visibility of the gridlines.
  406. super().grid(b, which=which, axis=axis, **kwargs)
  407. if not self._axisline_on:
  408. return
  409. if b is None:
  410. b = (self.axes.xaxis._minor_tick_kw["gridOn"]
  411. or self.axes.xaxis._major_tick_kw["gridOn"]
  412. or self.axes.yaxis._minor_tick_kw["gridOn"]
  413. or self.axes.yaxis._major_tick_kw["gridOn"])
  414. self.gridlines.set(which=which, axis=axis, visible=b)
  415. self.gridlines.set(**kwargs)
  416. def get_children(self):
  417. if self._axisline_on:
  418. children = [*self._axislines.values(), self.gridlines]
  419. else:
  420. children = []
  421. children.extend(super().get_children())
  422. return children
  423. def invalidate_grid_helper(self):
  424. self._grid_helper.invalidate()
  425. def new_fixed_axis(self, loc, offset=None):
  426. gh = self.get_grid_helper()
  427. axis = gh.new_fixed_axis(loc,
  428. nth_coord=None,
  429. axis_direction=None,
  430. offset=offset,
  431. axes=self,
  432. )
  433. return axis
  434. def new_floating_axis(self, nth_coord, value, axis_direction="bottom"):
  435. gh = self.get_grid_helper()
  436. axis = gh.new_floating_axis(nth_coord, value,
  437. axis_direction=axis_direction,
  438. axes=self)
  439. return axis
  440. Subplot = maxes.subplot_class_factory(Axes)
  441. class AxesZero(Axes):
  442. def _init_axis_artists(self):
  443. super()._init_axis_artists()
  444. new_floating_axis = self._grid_helper.new_floating_axis
  445. xaxis_zero = new_floating_axis(nth_coord=0,
  446. value=0.,
  447. axis_direction="bottom",
  448. axes=self)
  449. xaxis_zero.line.set_clip_path(self.patch)
  450. xaxis_zero.set_visible(False)
  451. self._axislines["xzero"] = xaxis_zero
  452. yaxis_zero = new_floating_axis(nth_coord=1,
  453. value=0.,
  454. axis_direction="left",
  455. axes=self)
  456. yaxis_zero.line.set_clip_path(self.patch)
  457. yaxis_zero.set_visible(False)
  458. self._axislines["yzero"] = yaxis_zero
  459. SubplotZero = maxes.subplot_class_factory(AxesZero)