axis3d.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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 numpy as np
  5. from matplotlib import (
  6. artist, cbook, lines as mlines, axis as maxis, patches as mpatches,
  7. rcParams)
  8. from . import art3d, proj3d
  9. @cbook.deprecated("3.1")
  10. def get_flip_min_max(coord, index, mins, maxs):
  11. if coord[index] == mins[index]:
  12. return maxs[index]
  13. else:
  14. return mins[index]
  15. def move_from_center(coord, centers, deltas, axmask=(True, True, True)):
  16. """
  17. For each coordinate where *axmask* is True, move *coord* away from
  18. *centers* by *deltas*.
  19. """
  20. coord = np.asarray(coord)
  21. return coord + axmask * np.copysign(1, coord - centers) * deltas
  22. def tick_update_position(tick, tickxs, tickys, labelpos):
  23. '''Update tick line and label position and style.'''
  24. tick.label1.set_position(labelpos)
  25. tick.label2.set_position(labelpos)
  26. tick.tick1line.set_visible(True)
  27. tick.tick2line.set_visible(False)
  28. tick.tick1line.set_linestyle('-')
  29. tick.tick1line.set_marker('')
  30. tick.tick1line.set_data(tickxs, tickys)
  31. tick.gridline.set_data(0, 0)
  32. class Axis(maxis.XAxis):
  33. """An Axis class for the 3D plots."""
  34. # These points from the unit cube make up the x, y and z-planes
  35. _PLANES = (
  36. (0, 3, 7, 4), (1, 2, 6, 5), # yz planes
  37. (0, 1, 5, 4), (3, 2, 6, 7), # xz planes
  38. (0, 1, 2, 3), (4, 5, 6, 7), # xy planes
  39. )
  40. # Some properties for the axes
  41. _AXINFO = {
  42. 'x': {'i': 0, 'tickdir': 1, 'juggled': (1, 0, 2),
  43. 'color': (0.95, 0.95, 0.95, 0.5)},
  44. 'y': {'i': 1, 'tickdir': 0, 'juggled': (0, 1, 2),
  45. 'color': (0.90, 0.90, 0.90, 0.5)},
  46. 'z': {'i': 2, 'tickdir': 0, 'juggled': (0, 2, 1),
  47. 'color': (0.925, 0.925, 0.925, 0.5)},
  48. }
  49. def __init__(self, adir, v_intervalx, d_intervalx, axes, *args,
  50. rotate_label=None, **kwargs):
  51. # adir identifies which axes this is
  52. self.adir = adir
  53. # This is a temporary member variable.
  54. # Do not depend on this existing in future releases!
  55. self._axinfo = self._AXINFO[adir].copy()
  56. if rcParams['_internal.classic_mode']:
  57. self._axinfo.update(
  58. {'label': {'va': 'center',
  59. 'ha': 'center'},
  60. 'tick': {'inward_factor': 0.2,
  61. 'outward_factor': 0.1,
  62. 'linewidth': rcParams['lines.linewidth']},
  63. 'axisline': {'linewidth': 0.75,
  64. 'color': (0, 0, 0, 1)},
  65. 'grid': {'color': (0.9, 0.9, 0.9, 1),
  66. 'linewidth': 1.0,
  67. 'linestyle': '-'},
  68. })
  69. else:
  70. self._axinfo.update(
  71. {'label': {'va': 'center',
  72. 'ha': 'center'},
  73. 'tick': {'inward_factor': 0.2,
  74. 'outward_factor': 0.1,
  75. 'linewidth': rcParams.get(
  76. adir + 'tick.major.width',
  77. rcParams['xtick.major.width'])},
  78. 'axisline': {'linewidth': rcParams['axes.linewidth'],
  79. 'color': rcParams['axes.edgecolor']},
  80. 'grid': {'color': rcParams['grid.color'],
  81. 'linewidth': rcParams['grid.linewidth'],
  82. 'linestyle': rcParams['grid.linestyle']},
  83. })
  84. maxis.XAxis.__init__(self, axes, *args, **kwargs)
  85. # data and viewing intervals for this direction
  86. self.d_interval = d_intervalx
  87. self.v_interval = v_intervalx
  88. self.set_rotate_label(rotate_label)
  89. def init3d(self):
  90. self.line = mlines.Line2D(
  91. xdata=(0, 0), ydata=(0, 0),
  92. linewidth=self._axinfo['axisline']['linewidth'],
  93. color=self._axinfo['axisline']['color'],
  94. antialiased=True)
  95. # Store dummy data in Polygon object
  96. self.pane = mpatches.Polygon(
  97. np.array([[0, 0], [0, 1], [1, 0], [0, 0]]),
  98. closed=False, alpha=0.8, facecolor='k', edgecolor='k')
  99. self.set_pane_color(self._axinfo['color'])
  100. self.axes._set_artist_props(self.line)
  101. self.axes._set_artist_props(self.pane)
  102. self.gridlines = art3d.Line3DCollection([])
  103. self.axes._set_artist_props(self.gridlines)
  104. self.axes._set_artist_props(self.label)
  105. self.axes._set_artist_props(self.offsetText)
  106. # Need to be able to place the label at the correct location
  107. self.label._transform = self.axes.transData
  108. self.offsetText._transform = self.axes.transData
  109. @cbook.deprecated("3.1")
  110. def get_tick_positions(self):
  111. majorLocs = self.major.locator()
  112. majorLabels = self.major.formatter.format_ticks(majorLocs)
  113. return majorLabels, majorLocs
  114. def get_major_ticks(self, numticks=None):
  115. ticks = maxis.XAxis.get_major_ticks(self, numticks)
  116. for t in ticks:
  117. t.tick1line.set_transform(self.axes.transData)
  118. t.tick2line.set_transform(self.axes.transData)
  119. t.gridline.set_transform(self.axes.transData)
  120. t.label1.set_transform(self.axes.transData)
  121. t.label2.set_transform(self.axes.transData)
  122. return ticks
  123. def set_pane_pos(self, xys):
  124. xys = np.asarray(xys)
  125. xys = xys[:, :2]
  126. self.pane.xy = xys
  127. self.stale = True
  128. def set_pane_color(self, color):
  129. '''Set pane color to a RGBA tuple.'''
  130. self._axinfo['color'] = color
  131. self.pane.set_edgecolor(color)
  132. self.pane.set_facecolor(color)
  133. self.pane.set_alpha(color[-1])
  134. self.stale = True
  135. def set_rotate_label(self, val):
  136. '''
  137. Whether to rotate the axis label: True, False or None.
  138. If set to None the label will be rotated if longer than 4 chars.
  139. '''
  140. self._rotate_label = val
  141. self.stale = True
  142. def get_rotate_label(self, text):
  143. if self._rotate_label is not None:
  144. return self._rotate_label
  145. else:
  146. return len(text) > 4
  147. def _get_coord_info(self, renderer):
  148. mins, maxs = np.array([
  149. self.axes.get_xbound(),
  150. self.axes.get_ybound(),
  151. self.axes.get_zbound(),
  152. ]).T
  153. centers = (maxs + mins) / 2.
  154. deltas = (maxs - mins) / 12.
  155. mins = mins - deltas / 4.
  156. maxs = maxs + deltas / 4.
  157. vals = mins[0], maxs[0], mins[1], maxs[1], mins[2], maxs[2]
  158. tc = self.axes.tunit_cube(vals, renderer.M)
  159. avgz = [tc[p1][2] + tc[p2][2] + tc[p3][2] + tc[p4][2]
  160. for p1, p2, p3, p4 in self._PLANES]
  161. highs = np.array([avgz[2*i] < avgz[2*i+1] for i in range(3)])
  162. return mins, maxs, centers, deltas, tc, highs
  163. def draw_pane(self, renderer):
  164. renderer.open_group('pane3d', gid=self.get_gid())
  165. mins, maxs, centers, deltas, tc, highs = self._get_coord_info(renderer)
  166. info = self._axinfo
  167. index = info['i']
  168. if not highs[index]:
  169. plane = self._PLANES[2 * index]
  170. else:
  171. plane = self._PLANES[2 * index + 1]
  172. xys = [tc[p] for p in plane]
  173. self.set_pane_pos(xys)
  174. self.pane.draw(renderer)
  175. renderer.close_group('pane3d')
  176. @artist.allow_rasterization
  177. def draw(self, renderer):
  178. self.label._transform = self.axes.transData
  179. renderer.open_group('axis3d', gid=self.get_gid())
  180. ticks = self._update_ticks()
  181. info = self._axinfo
  182. index = info['i']
  183. mins, maxs, centers, deltas, tc, highs = self._get_coord_info(renderer)
  184. # Determine grid lines
  185. minmax = np.where(highs, maxs, mins)
  186. maxmin = np.where(highs, mins, maxs)
  187. # Draw main axis line
  188. juggled = info['juggled']
  189. edgep1 = minmax.copy()
  190. edgep1[juggled[0]] = maxmin[juggled[0]]
  191. edgep2 = edgep1.copy()
  192. edgep2[juggled[1]] = maxmin[juggled[1]]
  193. pep = np.asarray(
  194. proj3d.proj_trans_points([edgep1, edgep2], renderer.M))
  195. centpt = proj3d.proj_transform(*centers, renderer.M)
  196. self.line.set_data(pep[0], pep[1])
  197. self.line.draw(renderer)
  198. # Grid points where the planes meet
  199. xyz0 = np.tile(minmax, (len(ticks), 1))
  200. xyz0[:, index] = [tick.get_loc() for tick in ticks]
  201. # Draw labels
  202. # The transAxes transform is used because the Text object
  203. # rotates the text relative to the display coordinate system.
  204. # Therefore, if we want the labels to remain parallel to the
  205. # axis regardless of the aspect ratio, we need to convert the
  206. # edge points of the plane to display coordinates and calculate
  207. # an angle from that.
  208. # TODO: Maybe Text objects should handle this themselves?
  209. dx, dy = (self.axes.transAxes.transform([pep[0:2, 1]]) -
  210. self.axes.transAxes.transform([pep[0:2, 0]]))[0]
  211. lxyz = 0.5 * (edgep1 + edgep2)
  212. # A rough estimate; points are ambiguous since 3D plots rotate
  213. ax_scale = self.axes.bbox.size / self.figure.bbox.size
  214. ax_inches = np.multiply(ax_scale, self.figure.get_size_inches())
  215. ax_points_estimate = sum(72. * ax_inches)
  216. deltas_per_point = 48 / ax_points_estimate
  217. default_offset = 21.
  218. labeldeltas = (
  219. (self.labelpad + default_offset) * deltas_per_point * deltas)
  220. axmask = [True, True, True]
  221. axmask[index] = False
  222. lxyz = move_from_center(lxyz, centers, labeldeltas, axmask)
  223. tlx, tly, tlz = proj3d.proj_transform(*lxyz, renderer.M)
  224. self.label.set_position((tlx, tly))
  225. if self.get_rotate_label(self.label.get_text()):
  226. angle = art3d._norm_text_angle(np.rad2deg(np.arctan2(dy, dx)))
  227. self.label.set_rotation(angle)
  228. self.label.set_va(info['label']['va'])
  229. self.label.set_ha(info['label']['ha'])
  230. self.label.draw(renderer)
  231. # Draw Offset text
  232. # Which of the two edge points do we want to
  233. # use for locating the offset text?
  234. if juggled[2] == 2:
  235. outeredgep = edgep1
  236. outerindex = 0
  237. else:
  238. outeredgep = edgep2
  239. outerindex = 1
  240. pos = move_from_center(outeredgep, centers, labeldeltas, axmask)
  241. olx, oly, olz = proj3d.proj_transform(*pos, renderer.M)
  242. self.offsetText.set_text(self.major.formatter.get_offset())
  243. self.offsetText.set_position((olx, oly))
  244. angle = art3d._norm_text_angle(np.rad2deg(np.arctan2(dy, dx)))
  245. self.offsetText.set_rotation(angle)
  246. # Must set rotation mode to "anchor" so that
  247. # the alignment point is used as the "fulcrum" for rotation.
  248. self.offsetText.set_rotation_mode('anchor')
  249. #----------------------------------------------------------------------
  250. # Note: the following statement for determining the proper alignment of
  251. # the offset text. This was determined entirely by trial-and-error
  252. # and should not be in any way considered as "the way". There are
  253. # still some edge cases where alignment is not quite right, but this
  254. # seems to be more of a geometry issue (in other words, I might be
  255. # using the wrong reference points).
  256. #
  257. # (TT, FF, TF, FT) are the shorthand for the tuple of
  258. # (centpt[info['tickdir']] <= pep[info['tickdir'], outerindex],
  259. # centpt[index] <= pep[index, outerindex])
  260. #
  261. # Three-letters (e.g., TFT, FTT) are short-hand for the array of bools
  262. # from the variable 'highs'.
  263. # ---------------------------------------------------------------------
  264. if centpt[info['tickdir']] > pep[info['tickdir'], outerindex]:
  265. # if FT and if highs has an even number of Trues
  266. if (centpt[index] <= pep[index, outerindex]
  267. and np.count_nonzero(highs) % 2 == 0):
  268. # Usually, this means align right, except for the FTT case,
  269. # in which offset for axis 1 and 2 are aligned left.
  270. if highs.tolist() == [False, True, True] and index in (1, 2):
  271. align = 'left'
  272. else:
  273. align = 'right'
  274. else:
  275. # The FF case
  276. align = 'left'
  277. else:
  278. # if TF and if highs has an even number of Trues
  279. if (centpt[index] > pep[index, outerindex]
  280. and np.count_nonzero(highs) % 2 == 0):
  281. # Usually mean align left, except if it is axis 2
  282. if index == 2:
  283. align = 'right'
  284. else:
  285. align = 'left'
  286. else:
  287. # The TT case
  288. align = 'right'
  289. self.offsetText.set_va('center')
  290. self.offsetText.set_ha(align)
  291. self.offsetText.draw(renderer)
  292. if self.axes._draw_grid and len(ticks):
  293. # Grid lines go from the end of one plane through the plane
  294. # intersection (at xyz0) to the end of the other plane. The first
  295. # point (0) differs along dimension index-2 and the last (2) along
  296. # dimension index-1.
  297. lines = np.stack([xyz0, xyz0, xyz0], axis=1)
  298. lines[:, 0, index - 2] = maxmin[index - 2]
  299. lines[:, 2, index - 1] = maxmin[index - 1]
  300. self.gridlines.set_segments(lines)
  301. self.gridlines.set_color(info['grid']['color'])
  302. self.gridlines.set_linewidth(info['grid']['linewidth'])
  303. self.gridlines.set_linestyle(info['grid']['linestyle'])
  304. self.gridlines.draw(renderer, project=True)
  305. # Draw ticks
  306. tickdir = info['tickdir']
  307. tickdelta = deltas[tickdir]
  308. if highs[tickdir]:
  309. ticksign = 1
  310. else:
  311. ticksign = -1
  312. for tick in ticks:
  313. # Get tick line positions
  314. pos = edgep1.copy()
  315. pos[index] = tick.get_loc()
  316. pos[tickdir] = (
  317. edgep1[tickdir]
  318. + info['tick']['outward_factor'] * ticksign * tickdelta)
  319. x1, y1, z1 = proj3d.proj_transform(*pos, renderer.M)
  320. pos[tickdir] = (
  321. edgep1[tickdir]
  322. - info['tick']['inward_factor'] * ticksign * tickdelta)
  323. x2, y2, z2 = proj3d.proj_transform(*pos, renderer.M)
  324. # Get position of label
  325. default_offset = 8. # A rough estimate
  326. labeldeltas = (
  327. (tick.get_pad() + default_offset) * deltas_per_point * deltas)
  328. axmask = [True, True, True]
  329. axmask[index] = False
  330. pos[tickdir] = edgep1[tickdir]
  331. pos = move_from_center(pos, centers, labeldeltas, axmask)
  332. lx, ly, lz = proj3d.proj_transform(*pos, renderer.M)
  333. tick_update_position(tick, (x1, x2), (y1, y2), (lx, ly))
  334. tick.tick1line.set_linewidth(info['tick']['linewidth'])
  335. tick.draw(renderer)
  336. renderer.close_group('axis3d')
  337. self.stale = False
  338. # TODO: Get this to work properly when mplot3d supports
  339. # the transforms framework.
  340. def get_tightbbox(self, renderer):
  341. # Currently returns None so that Axis.get_tightbbox
  342. # doesn't return junk info.
  343. return None
  344. @property
  345. def d_interval(self):
  346. return self.get_data_interval()
  347. @d_interval.setter
  348. def d_interval(self, minmax):
  349. return self.set_data_interval(*minmax)
  350. @property
  351. def v_interval(self):
  352. return self.get_view_interval()
  353. @v_interval.setter
  354. def v_interval(self, minmax):
  355. return self.set_view_interval(*minmax)
  356. # Use classes to look at different data limits
  357. class XAxis(Axis):
  358. get_view_interval, set_view_interval = maxis._make_getset_interval(
  359. "view", "xy_viewLim", "intervalx")
  360. get_data_interval, set_data_interval = maxis._make_getset_interval(
  361. "data", "xy_dataLim", "intervalx")
  362. class YAxis(Axis):
  363. get_view_interval, set_view_interval = maxis._make_getset_interval(
  364. "view", "xy_viewLim", "intervaly")
  365. get_data_interval, set_data_interval = maxis._make_getset_interval(
  366. "data", "xy_dataLim", "intervaly")
  367. class ZAxis(Axis):
  368. get_view_interval, set_view_interval = maxis._make_getset_interval(
  369. "view", "zz_viewLim", "intervalx")
  370. get_data_interval, set_data_interval = maxis._make_getset_interval(
  371. "data", "zz_dataLim", "intervalx")