axis3d.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753
  1. # axis3d.py, original mplot3d version by John Porter
  2. # Created: 23 Sep 2005
  3. # Parts rewritten by Reinier Heeres <reinier@heeres.eu>
  4. import inspect
  5. import numpy as np
  6. import matplotlib as mpl
  7. from matplotlib import (
  8. _api, artist, lines as mlines, axis as maxis, patches as mpatches,
  9. transforms as mtransforms, colors as mcolors)
  10. from . import art3d, proj3d
  11. def _move_from_center(coord, centers, deltas, axmask=(True, True, True)):
  12. """
  13. For each coordinate where *axmask* is True, move *coord* away from
  14. *centers* by *deltas*.
  15. """
  16. coord = np.asarray(coord)
  17. return coord + axmask * np.copysign(1, coord - centers) * deltas
  18. def _tick_update_position(tick, tickxs, tickys, labelpos):
  19. """Update tick line and label position and style."""
  20. tick.label1.set_position(labelpos)
  21. tick.label2.set_position(labelpos)
  22. tick.tick1line.set_visible(True)
  23. tick.tick2line.set_visible(False)
  24. tick.tick1line.set_linestyle('-')
  25. tick.tick1line.set_marker('')
  26. tick.tick1line.set_data(tickxs, tickys)
  27. tick.gridline.set_data([0], [0])
  28. class Axis(maxis.XAxis):
  29. """An Axis class for the 3D plots."""
  30. # These points from the unit cube make up the x, y and z-planes
  31. _PLANES = (
  32. (0, 3, 7, 4), (1, 2, 6, 5), # yz planes
  33. (0, 1, 5, 4), (3, 2, 6, 7), # xz planes
  34. (0, 1, 2, 3), (4, 5, 6, 7), # xy planes
  35. )
  36. # Some properties for the axes
  37. _AXINFO = {
  38. 'x': {'i': 0, 'tickdir': 1, 'juggled': (1, 0, 2)},
  39. 'y': {'i': 1, 'tickdir': 0, 'juggled': (0, 1, 2)},
  40. 'z': {'i': 2, 'tickdir': 0, 'juggled': (0, 2, 1)},
  41. }
  42. def _old_init(self, adir, v_intervalx, d_intervalx, axes, *args,
  43. rotate_label=None, **kwargs):
  44. return locals()
  45. def _new_init(self, axes, *, rotate_label=None, **kwargs):
  46. return locals()
  47. def __init__(self, *args, **kwargs):
  48. params = _api.select_matching_signature(
  49. [self._old_init, self._new_init], *args, **kwargs)
  50. if "adir" in params:
  51. _api.warn_deprecated(
  52. "3.6", message=f"The signature of 3D Axis constructors has "
  53. f"changed in %(since)s; the new signature is "
  54. f"{inspect.signature(type(self).__init__)}", pending=True)
  55. if params["adir"] != self.axis_name:
  56. raise ValueError(f"Cannot instantiate {type(self).__name__} "
  57. f"with adir={params['adir']!r}")
  58. axes = params["axes"]
  59. rotate_label = params["rotate_label"]
  60. args = params.get("args", ())
  61. kwargs = params["kwargs"]
  62. name = self.axis_name
  63. self._label_position = 'default'
  64. self._tick_position = 'default'
  65. # This is a temporary member variable.
  66. # Do not depend on this existing in future releases!
  67. self._axinfo = self._AXINFO[name].copy()
  68. # Common parts
  69. self._axinfo.update({
  70. 'label': {'va': 'center', 'ha': 'center',
  71. 'rotation_mode': 'anchor'},
  72. 'color': mpl.rcParams[f'axes3d.{name}axis.panecolor'],
  73. 'tick': {
  74. 'inward_factor': 0.2,
  75. 'outward_factor': 0.1,
  76. },
  77. })
  78. if mpl.rcParams['_internal.classic_mode']:
  79. self._axinfo.update({
  80. 'axisline': {'linewidth': 0.75, 'color': (0, 0, 0, 1)},
  81. 'grid': {
  82. 'color': (0.9, 0.9, 0.9, 1),
  83. 'linewidth': 1.0,
  84. 'linestyle': '-',
  85. },
  86. })
  87. self._axinfo['tick'].update({
  88. 'linewidth': {
  89. True: mpl.rcParams['lines.linewidth'], # major
  90. False: mpl.rcParams['lines.linewidth'], # minor
  91. }
  92. })
  93. else:
  94. self._axinfo.update({
  95. 'axisline': {
  96. 'linewidth': mpl.rcParams['axes.linewidth'],
  97. 'color': mpl.rcParams['axes.edgecolor'],
  98. },
  99. 'grid': {
  100. 'color': mpl.rcParams['grid.color'],
  101. 'linewidth': mpl.rcParams['grid.linewidth'],
  102. 'linestyle': mpl.rcParams['grid.linestyle'],
  103. },
  104. })
  105. self._axinfo['tick'].update({
  106. 'linewidth': {
  107. True: ( # major
  108. mpl.rcParams['xtick.major.width'] if name in 'xz'
  109. else mpl.rcParams['ytick.major.width']),
  110. False: ( # minor
  111. mpl.rcParams['xtick.minor.width'] if name in 'xz'
  112. else mpl.rcParams['ytick.minor.width']),
  113. }
  114. })
  115. super().__init__(axes, *args, **kwargs)
  116. # data and viewing intervals for this direction
  117. if "d_intervalx" in params:
  118. self.set_data_interval(*params["d_intervalx"])
  119. if "v_intervalx" in params:
  120. self.set_view_interval(*params["v_intervalx"])
  121. self.set_rotate_label(rotate_label)
  122. self._init3d() # Inline after init3d deprecation elapses.
  123. __init__.__signature__ = inspect.signature(_new_init)
  124. adir = _api.deprecated("3.6", pending=True)(
  125. property(lambda self: self.axis_name))
  126. def _init3d(self):
  127. self.line = mlines.Line2D(
  128. xdata=(0, 0), ydata=(0, 0),
  129. linewidth=self._axinfo['axisline']['linewidth'],
  130. color=self._axinfo['axisline']['color'],
  131. antialiased=True)
  132. # Store dummy data in Polygon object
  133. self.pane = mpatches.Polygon([[0, 0], [0, 1]], closed=False)
  134. self.set_pane_color(self._axinfo['color'])
  135. self.axes._set_artist_props(self.line)
  136. self.axes._set_artist_props(self.pane)
  137. self.gridlines = art3d.Line3DCollection([])
  138. self.axes._set_artist_props(self.gridlines)
  139. self.axes._set_artist_props(self.label)
  140. self.axes._set_artist_props(self.offsetText)
  141. # Need to be able to place the label at the correct location
  142. self.label._transform = self.axes.transData
  143. self.offsetText._transform = self.axes.transData
  144. @_api.deprecated("3.6", pending=True)
  145. def init3d(self): # After deprecation elapses, inline _init3d to __init__.
  146. self._init3d()
  147. def get_major_ticks(self, numticks=None):
  148. ticks = super().get_major_ticks(numticks)
  149. for t in ticks:
  150. for obj in [
  151. t.tick1line, t.tick2line, t.gridline, t.label1, t.label2]:
  152. obj.set_transform(self.axes.transData)
  153. return ticks
  154. def get_minor_ticks(self, numticks=None):
  155. ticks = super().get_minor_ticks(numticks)
  156. for t in ticks:
  157. for obj in [
  158. t.tick1line, t.tick2line, t.gridline, t.label1, t.label2]:
  159. obj.set_transform(self.axes.transData)
  160. return ticks
  161. def set_ticks_position(self, position):
  162. """
  163. Set the ticks position.
  164. Parameters
  165. ----------
  166. position : {'lower', 'upper', 'both', 'default', 'none'}
  167. The position of the bolded axis lines, ticks, and tick labels.
  168. """
  169. if position in ['top', 'bottom']:
  170. _api.warn_deprecated('3.8', name=f'{position=}',
  171. obj_type='argument value',
  172. alternative="'upper' or 'lower'")
  173. return
  174. _api.check_in_list(['lower', 'upper', 'both', 'default', 'none'],
  175. position=position)
  176. self._tick_position = position
  177. def get_ticks_position(self):
  178. """
  179. Get the ticks position.
  180. Returns
  181. -------
  182. str : {'lower', 'upper', 'both', 'default', 'none'}
  183. The position of the bolded axis lines, ticks, and tick labels.
  184. """
  185. return self._tick_position
  186. def set_label_position(self, position):
  187. """
  188. Set the label position.
  189. Parameters
  190. ----------
  191. position : {'lower', 'upper', 'both', 'default', 'none'}
  192. The position of the axis label.
  193. """
  194. if position in ['top', 'bottom']:
  195. _api.warn_deprecated('3.8', name=f'{position=}',
  196. obj_type='argument value',
  197. alternative="'upper' or 'lower'")
  198. return
  199. _api.check_in_list(['lower', 'upper', 'both', 'default', 'none'],
  200. position=position)
  201. self._label_position = position
  202. def get_label_position(self):
  203. """
  204. Get the label position.
  205. Returns
  206. -------
  207. str : {'lower', 'upper', 'both', 'default', 'none'}
  208. The position of the axis label.
  209. """
  210. return self._label_position
  211. def set_pane_color(self, color, alpha=None):
  212. """
  213. Set pane color.
  214. Parameters
  215. ----------
  216. color : color
  217. Color for axis pane.
  218. alpha : float, optional
  219. Alpha value for axis pane. If None, base it on *color*.
  220. """
  221. color = mcolors.to_rgba(color, alpha)
  222. self._axinfo['color'] = color
  223. self.pane.set_edgecolor(color)
  224. self.pane.set_facecolor(color)
  225. self.pane.set_alpha(color[-1])
  226. self.stale = True
  227. def set_rotate_label(self, val):
  228. """
  229. Whether to rotate the axis label: True, False or None.
  230. If set to None the label will be rotated if longer than 4 chars.
  231. """
  232. self._rotate_label = val
  233. self.stale = True
  234. def get_rotate_label(self, text):
  235. if self._rotate_label is not None:
  236. return self._rotate_label
  237. else:
  238. return len(text) > 4
  239. def _get_coord_info(self, renderer):
  240. mins, maxs = np.array([
  241. self.axes.get_xbound(),
  242. self.axes.get_ybound(),
  243. self.axes.get_zbound(),
  244. ]).T
  245. # Get the mean value for each bound:
  246. centers = 0.5 * (maxs + mins)
  247. # Add a small offset between min/max point and the edge of the plot:
  248. deltas = (maxs - mins) / 12
  249. mins -= 0.25 * deltas
  250. maxs += 0.25 * deltas
  251. # Project the bounds along the current position of the cube:
  252. bounds = mins[0], maxs[0], mins[1], maxs[1], mins[2], maxs[2]
  253. bounds_proj = self.axes._tunit_cube(bounds, self.axes.M)
  254. # Determine which one of the parallel planes are higher up:
  255. means_z0 = np.zeros(3)
  256. means_z1 = np.zeros(3)
  257. for i in range(3):
  258. means_z0[i] = np.mean(bounds_proj[self._PLANES[2 * i], 2])
  259. means_z1[i] = np.mean(bounds_proj[self._PLANES[2 * i + 1], 2])
  260. highs = means_z0 < means_z1
  261. # Special handling for edge-on views
  262. equals = np.abs(means_z0 - means_z1) <= np.finfo(float).eps
  263. if np.sum(equals) == 2:
  264. vertical = np.where(~equals)[0][0]
  265. if vertical == 2: # looking at XY plane
  266. highs = np.array([True, True, highs[2]])
  267. elif vertical == 1: # looking at XZ plane
  268. highs = np.array([True, highs[1], False])
  269. elif vertical == 0: # looking at YZ plane
  270. highs = np.array([highs[0], False, False])
  271. return mins, maxs, centers, deltas, bounds_proj, highs
  272. def _get_axis_line_edge_points(self, minmax, maxmin, position=None):
  273. """Get the edge points for the black bolded axis line."""
  274. # When changing vertical axis some of the axes has to be
  275. # moved to the other plane so it looks the same as if the z-axis
  276. # was the vertical axis.
  277. mb = [minmax, maxmin] # line from origin to nearest corner to camera
  278. mb_rev = mb[::-1]
  279. mm = [[mb, mb_rev, mb_rev], [mb_rev, mb_rev, mb], [mb, mb, mb]]
  280. mm = mm[self.axes._vertical_axis][self._axinfo["i"]]
  281. juggled = self._axinfo["juggled"]
  282. edge_point_0 = mm[0].copy() # origin point
  283. if ((position == 'lower' and mm[1][juggled[-1]] < mm[0][juggled[-1]]) or
  284. (position == 'upper' and mm[1][juggled[-1]] > mm[0][juggled[-1]])):
  285. edge_point_0[juggled[-1]] = mm[1][juggled[-1]]
  286. else:
  287. edge_point_0[juggled[0]] = mm[1][juggled[0]]
  288. edge_point_1 = edge_point_0.copy()
  289. edge_point_1[juggled[1]] = mm[1][juggled[1]]
  290. return edge_point_0, edge_point_1
  291. def _get_all_axis_line_edge_points(self, minmax, maxmin, axis_position=None):
  292. # Determine edge points for the axis lines
  293. edgep1s = []
  294. edgep2s = []
  295. position = []
  296. if axis_position in (None, 'default'):
  297. edgep1, edgep2 = self._get_axis_line_edge_points(minmax, maxmin)
  298. edgep1s = [edgep1]
  299. edgep2s = [edgep2]
  300. position = ['default']
  301. else:
  302. edgep1_l, edgep2_l = self._get_axis_line_edge_points(minmax, maxmin,
  303. position='lower')
  304. edgep1_u, edgep2_u = self._get_axis_line_edge_points(minmax, maxmin,
  305. position='upper')
  306. if axis_position in ('lower', 'both'):
  307. edgep1s.append(edgep1_l)
  308. edgep2s.append(edgep2_l)
  309. position.append('lower')
  310. if axis_position in ('upper', 'both'):
  311. edgep1s.append(edgep1_u)
  312. edgep2s.append(edgep2_u)
  313. position.append('upper')
  314. return edgep1s, edgep2s, position
  315. def _get_tickdir(self, position):
  316. """
  317. Get the direction of the tick.
  318. Parameters
  319. ----------
  320. position : str, optional : {'upper', 'lower', 'default'}
  321. The position of the axis.
  322. Returns
  323. -------
  324. tickdir : int
  325. Index which indicates which coordinate the tick line will
  326. align with.
  327. """
  328. _api.check_in_list(('upper', 'lower', 'default'), position=position)
  329. # TODO: Move somewhere else where it's triggered less:
  330. tickdirs_base = [v["tickdir"] for v in self._AXINFO.values()] # default
  331. elev_mod = np.mod(self.axes.elev + 180, 360) - 180
  332. azim_mod = np.mod(self.axes.azim, 360)
  333. if position == 'upper':
  334. if elev_mod >= 0:
  335. tickdirs_base = [2, 2, 0]
  336. else:
  337. tickdirs_base = [1, 0, 0]
  338. if 0 <= azim_mod < 180:
  339. tickdirs_base[2] = 1
  340. elif position == 'lower':
  341. if elev_mod >= 0:
  342. tickdirs_base = [1, 0, 1]
  343. else:
  344. tickdirs_base = [2, 2, 1]
  345. if 0 <= azim_mod < 180:
  346. tickdirs_base[2] = 0
  347. info_i = [v["i"] for v in self._AXINFO.values()]
  348. i = self._axinfo["i"]
  349. vert_ax = self.axes._vertical_axis
  350. j = vert_ax - 2
  351. # default: tickdir = [[1, 2, 1], [2, 2, 0], [1, 0, 0]][vert_ax][i]
  352. tickdir = np.roll(info_i, -j)[np.roll(tickdirs_base, j)][i]
  353. return tickdir
  354. def active_pane(self, renderer):
  355. mins, maxs, centers, deltas, tc, highs = self._get_coord_info(renderer)
  356. info = self._axinfo
  357. index = info['i']
  358. if not highs[index]:
  359. loc = mins[index]
  360. plane = self._PLANES[2 * index]
  361. else:
  362. loc = maxs[index]
  363. plane = self._PLANES[2 * index + 1]
  364. xys = np.array([tc[p] for p in plane])
  365. return xys, loc
  366. def draw_pane(self, renderer):
  367. """
  368. Draw pane.
  369. Parameters
  370. ----------
  371. renderer : `~matplotlib.backend_bases.RendererBase` subclass
  372. """
  373. renderer.open_group('pane3d', gid=self.get_gid())
  374. xys, loc = self.active_pane(renderer)
  375. self.pane.xy = xys[:, :2]
  376. self.pane.draw(renderer)
  377. renderer.close_group('pane3d')
  378. def _axmask(self):
  379. axmask = [True, True, True]
  380. axmask[self._axinfo["i"]] = False
  381. return axmask
  382. def _draw_ticks(self, renderer, edgep1, centers, deltas, highs,
  383. deltas_per_point, pos):
  384. ticks = self._update_ticks()
  385. info = self._axinfo
  386. index = info["i"]
  387. # Draw ticks:
  388. tickdir = self._get_tickdir(pos)
  389. tickdelta = deltas[tickdir] if highs[tickdir] else -deltas[tickdir]
  390. tick_info = info['tick']
  391. tick_out = tick_info['outward_factor'] * tickdelta
  392. tick_in = tick_info['inward_factor'] * tickdelta
  393. tick_lw = tick_info['linewidth']
  394. edgep1_tickdir = edgep1[tickdir]
  395. out_tickdir = edgep1_tickdir + tick_out
  396. in_tickdir = edgep1_tickdir - tick_in
  397. default_label_offset = 8. # A rough estimate
  398. points = deltas_per_point * deltas
  399. for tick in ticks:
  400. # Get tick line positions
  401. pos = edgep1.copy()
  402. pos[index] = tick.get_loc()
  403. pos[tickdir] = out_tickdir
  404. x1, y1, z1 = proj3d.proj_transform(*pos, self.axes.M)
  405. pos[tickdir] = in_tickdir
  406. x2, y2, z2 = proj3d.proj_transform(*pos, self.axes.M)
  407. # Get position of label
  408. labeldeltas = (tick.get_pad() + default_label_offset) * points
  409. pos[tickdir] = edgep1_tickdir
  410. pos = _move_from_center(pos, centers, labeldeltas, self._axmask())
  411. lx, ly, lz = proj3d.proj_transform(*pos, self.axes.M)
  412. _tick_update_position(tick, (x1, x2), (y1, y2), (lx, ly))
  413. tick.tick1line.set_linewidth(tick_lw[tick._major])
  414. tick.draw(renderer)
  415. def _draw_offset_text(self, renderer, edgep1, edgep2, labeldeltas, centers,
  416. highs, pep, dx, dy):
  417. # Get general axis information:
  418. info = self._axinfo
  419. index = info["i"]
  420. juggled = info["juggled"]
  421. tickdir = info["tickdir"]
  422. # Which of the two edge points do we want to
  423. # use for locating the offset text?
  424. if juggled[2] == 2:
  425. outeredgep = edgep1
  426. outerindex = 0
  427. else:
  428. outeredgep = edgep2
  429. outerindex = 1
  430. pos = _move_from_center(outeredgep, centers, labeldeltas,
  431. self._axmask())
  432. olx, oly, olz = proj3d.proj_transform(*pos, self.axes.M)
  433. self.offsetText.set_text(self.major.formatter.get_offset())
  434. self.offsetText.set_position((olx, oly))
  435. angle = art3d._norm_text_angle(np.rad2deg(np.arctan2(dy, dx)))
  436. self.offsetText.set_rotation(angle)
  437. # Must set rotation mode to "anchor" so that
  438. # the alignment point is used as the "fulcrum" for rotation.
  439. self.offsetText.set_rotation_mode('anchor')
  440. # ----------------------------------------------------------------------
  441. # Note: the following statement for determining the proper alignment of
  442. # the offset text. This was determined entirely by trial-and-error
  443. # and should not be in any way considered as "the way". There are
  444. # still some edge cases where alignment is not quite right, but this
  445. # seems to be more of a geometry issue (in other words, I might be
  446. # using the wrong reference points).
  447. #
  448. # (TT, FF, TF, FT) are the shorthand for the tuple of
  449. # (centpt[tickdir] <= pep[tickdir, outerindex],
  450. # centpt[index] <= pep[index, outerindex])
  451. #
  452. # Three-letters (e.g., TFT, FTT) are short-hand for the array of bools
  453. # from the variable 'highs'.
  454. # ---------------------------------------------------------------------
  455. centpt = proj3d.proj_transform(*centers, self.axes.M)
  456. if centpt[tickdir] > pep[tickdir, outerindex]:
  457. # if FT and if highs has an even number of Trues
  458. if (centpt[index] <= pep[index, outerindex]
  459. and np.count_nonzero(highs) % 2 == 0):
  460. # Usually, this means align right, except for the FTT case,
  461. # in which offset for axis 1 and 2 are aligned left.
  462. if highs.tolist() == [False, True, True] and index in (1, 2):
  463. align = 'left'
  464. else:
  465. align = 'right'
  466. else:
  467. # The FF case
  468. align = 'left'
  469. else:
  470. # if TF and if highs has an even number of Trues
  471. if (centpt[index] > pep[index, outerindex]
  472. and np.count_nonzero(highs) % 2 == 0):
  473. # Usually mean align left, except if it is axis 2
  474. align = 'right' if index == 2 else 'left'
  475. else:
  476. # The TT case
  477. align = 'right'
  478. self.offsetText.set_va('center')
  479. self.offsetText.set_ha(align)
  480. self.offsetText.draw(renderer)
  481. def _draw_labels(self, renderer, edgep1, edgep2, labeldeltas, centers, dx, dy):
  482. label = self._axinfo["label"]
  483. # Draw labels
  484. lxyz = 0.5 * (edgep1 + edgep2)
  485. lxyz = _move_from_center(lxyz, centers, labeldeltas, self._axmask())
  486. tlx, tly, tlz = proj3d.proj_transform(*lxyz, self.axes.M)
  487. self.label.set_position((tlx, tly))
  488. if self.get_rotate_label(self.label.get_text()):
  489. angle = art3d._norm_text_angle(np.rad2deg(np.arctan2(dy, dx)))
  490. self.label.set_rotation(angle)
  491. self.label.set_va(label['va'])
  492. self.label.set_ha(label['ha'])
  493. self.label.set_rotation_mode(label['rotation_mode'])
  494. self.label.draw(renderer)
  495. @artist.allow_rasterization
  496. def draw(self, renderer):
  497. self.label._transform = self.axes.transData
  498. self.offsetText._transform = self.axes.transData
  499. renderer.open_group("axis3d", gid=self.get_gid())
  500. # Get general axis information:
  501. mins, maxs, centers, deltas, tc, highs = self._get_coord_info(renderer)
  502. # Calculate offset distances
  503. # A rough estimate; points are ambiguous since 3D plots rotate
  504. reltoinches = self.figure.dpi_scale_trans.inverted()
  505. ax_inches = reltoinches.transform(self.axes.bbox.size)
  506. ax_points_estimate = sum(72. * ax_inches)
  507. deltas_per_point = 48 / ax_points_estimate
  508. default_offset = 21.
  509. labeldeltas = (self.labelpad + default_offset) * deltas_per_point * deltas
  510. # Determine edge points for the axis lines
  511. minmax = np.where(highs, maxs, mins) # "origin" point
  512. maxmin = np.where(~highs, maxs, mins) # "opposite" corner near camera
  513. for edgep1, edgep2, pos in zip(*self._get_all_axis_line_edge_points(
  514. minmax, maxmin, self._tick_position)):
  515. # Project the edge points along the current position
  516. pep = proj3d._proj_trans_points([edgep1, edgep2], self.axes.M)
  517. pep = np.asarray(pep)
  518. # The transAxes transform is used because the Text object
  519. # rotates the text relative to the display coordinate system.
  520. # Therefore, if we want the labels to remain parallel to the
  521. # axis regardless of the aspect ratio, we need to convert the
  522. # edge points of the plane to display coordinates and calculate
  523. # an angle from that.
  524. # TODO: Maybe Text objects should handle this themselves?
  525. dx, dy = (self.axes.transAxes.transform([pep[0:2, 1]]) -
  526. self.axes.transAxes.transform([pep[0:2, 0]]))[0]
  527. # Draw the lines
  528. self.line.set_data(pep[0], pep[1])
  529. self.line.draw(renderer)
  530. # Draw ticks
  531. self._draw_ticks(renderer, edgep1, centers, deltas, highs,
  532. deltas_per_point, pos)
  533. # Draw Offset text
  534. self._draw_offset_text(renderer, edgep1, edgep2, labeldeltas,
  535. centers, highs, pep, dx, dy)
  536. for edgep1, edgep2, pos in zip(*self._get_all_axis_line_edge_points(
  537. minmax, maxmin, self._label_position)):
  538. # See comments above
  539. pep = proj3d._proj_trans_points([edgep1, edgep2], self.axes.M)
  540. pep = np.asarray(pep)
  541. dx, dy = (self.axes.transAxes.transform([pep[0:2, 1]]) -
  542. self.axes.transAxes.transform([pep[0:2, 0]]))[0]
  543. # Draw labels
  544. self._draw_labels(renderer, edgep1, edgep2, labeldeltas, centers, dx, dy)
  545. renderer.close_group('axis3d')
  546. self.stale = False
  547. @artist.allow_rasterization
  548. def draw_grid(self, renderer):
  549. if not self.axes._draw_grid:
  550. return
  551. renderer.open_group("grid3d", gid=self.get_gid())
  552. ticks = self._update_ticks()
  553. if len(ticks):
  554. # Get general axis information:
  555. info = self._axinfo
  556. index = info["i"]
  557. mins, maxs, _, _, _, highs = self._get_coord_info(renderer)
  558. minmax = np.where(highs, maxs, mins)
  559. maxmin = np.where(~highs, maxs, mins)
  560. # Grid points where the planes meet
  561. xyz0 = np.tile(minmax, (len(ticks), 1))
  562. xyz0[:, index] = [tick.get_loc() for tick in ticks]
  563. # Grid lines go from the end of one plane through the plane
  564. # intersection (at xyz0) to the end of the other plane. The first
  565. # point (0) differs along dimension index-2 and the last (2) along
  566. # dimension index-1.
  567. lines = np.stack([xyz0, xyz0, xyz0], axis=1)
  568. lines[:, 0, index - 2] = maxmin[index - 2]
  569. lines[:, 2, index - 1] = maxmin[index - 1]
  570. self.gridlines.set_segments(lines)
  571. gridinfo = info['grid']
  572. self.gridlines.set_color(gridinfo['color'])
  573. self.gridlines.set_linewidth(gridinfo['linewidth'])
  574. self.gridlines.set_linestyle(gridinfo['linestyle'])
  575. self.gridlines.do_3d_projection()
  576. self.gridlines.draw(renderer)
  577. renderer.close_group('grid3d')
  578. # TODO: Get this to work (more) properly when mplot3d supports the
  579. # transforms framework.
  580. def get_tightbbox(self, renderer=None, *, for_layout_only=False):
  581. # docstring inherited
  582. if not self.get_visible():
  583. return
  584. # We have to directly access the internal data structures
  585. # (and hope they are up to date) because at draw time we
  586. # shift the ticks and their labels around in (x, y) space
  587. # based on the projection, the current view port, and their
  588. # position in 3D space. If we extend the transforms framework
  589. # into 3D we would not need to do this different book keeping
  590. # than we do in the normal axis
  591. major_locs = self.get_majorticklocs()
  592. minor_locs = self.get_minorticklocs()
  593. ticks = [*self.get_minor_ticks(len(minor_locs)),
  594. *self.get_major_ticks(len(major_locs))]
  595. view_low, view_high = self.get_view_interval()
  596. if view_low > view_high:
  597. view_low, view_high = view_high, view_low
  598. interval_t = self.get_transform().transform([view_low, view_high])
  599. ticks_to_draw = []
  600. for tick in ticks:
  601. try:
  602. loc_t = self.get_transform().transform(tick.get_loc())
  603. except AssertionError:
  604. # Transform.transform doesn't allow masked values but
  605. # some scales might make them, so we need this try/except.
  606. pass
  607. else:
  608. if mtransforms._interval_contains_close(interval_t, loc_t):
  609. ticks_to_draw.append(tick)
  610. ticks = ticks_to_draw
  611. bb_1, bb_2 = self._get_ticklabel_bboxes(ticks, renderer)
  612. other = []
  613. if self.line.get_visible():
  614. other.append(self.line.get_window_extent(renderer))
  615. if (self.label.get_visible() and not for_layout_only and
  616. self.label.get_text()):
  617. other.append(self.label.get_window_extent(renderer))
  618. return mtransforms.Bbox.union([*bb_1, *bb_2, *other])
  619. d_interval = _api.deprecated(
  620. "3.6", alternative="get_data_interval", pending=True)(
  621. property(lambda self: self.get_data_interval(),
  622. lambda self, minmax: self.set_data_interval(*minmax)))
  623. v_interval = _api.deprecated(
  624. "3.6", alternative="get_view_interval", pending=True)(
  625. property(lambda self: self.get_view_interval(),
  626. lambda self, minmax: self.set_view_interval(*minmax)))
  627. class XAxis(Axis):
  628. axis_name = "x"
  629. get_view_interval, set_view_interval = maxis._make_getset_interval(
  630. "view", "xy_viewLim", "intervalx")
  631. get_data_interval, set_data_interval = maxis._make_getset_interval(
  632. "data", "xy_dataLim", "intervalx")
  633. class YAxis(Axis):
  634. axis_name = "y"
  635. get_view_interval, set_view_interval = maxis._make_getset_interval(
  636. "view", "xy_viewLim", "intervaly")
  637. get_data_interval, set_data_interval = maxis._make_getset_interval(
  638. "data", "xy_dataLim", "intervaly")
  639. class ZAxis(Axis):
  640. axis_name = "z"
  641. get_view_interval, set_view_interval = maxis._make_getset_interval(
  642. "view", "zz_viewLim", "intervalx")
  643. get_data_interval, set_data_interval = maxis._make_getset_interval(
  644. "data", "zz_dataLim", "intervalx")