test_skew.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. """
  2. Testing that skewed axes properly work.
  3. """
  4. from contextlib import ExitStack
  5. import itertools
  6. import matplotlib.pyplot as plt
  7. from matplotlib.testing.decorators import image_comparison
  8. from matplotlib.axes import Axes
  9. import matplotlib.transforms as transforms
  10. import matplotlib.axis as maxis
  11. import matplotlib.spines as mspines
  12. import matplotlib.patches as mpatch
  13. from matplotlib.projections import register_projection
  14. # The sole purpose of this class is to look at the upper, lower, or total
  15. # interval as appropriate and see what parts of the tick to draw, if any.
  16. class SkewXTick(maxis.XTick):
  17. def draw(self, renderer):
  18. with ExitStack() as stack:
  19. for artist in [self.gridline, self.tick1line, self.tick2line,
  20. self.label1, self.label2]:
  21. stack.callback(artist.set_visible, artist.get_visible())
  22. needs_lower = transforms.interval_contains(
  23. self.axes.lower_xlim, self.get_loc())
  24. needs_upper = transforms.interval_contains(
  25. self.axes.upper_xlim, self.get_loc())
  26. self.tick1line.set_visible(
  27. self.tick1line.get_visible() and needs_lower)
  28. self.label1.set_visible(
  29. self.label1.get_visible() and needs_lower)
  30. self.tick2line.set_visible(
  31. self.tick2line.get_visible() and needs_upper)
  32. self.label2.set_visible(
  33. self.label2.get_visible() and needs_upper)
  34. super(SkewXTick, self).draw(renderer)
  35. def get_view_interval(self):
  36. return self.axes.xaxis.get_view_interval()
  37. # This class exists to provide two separate sets of intervals to the tick,
  38. # as well as create instances of the custom tick
  39. class SkewXAxis(maxis.XAxis):
  40. def _get_tick(self, major):
  41. return SkewXTick(self.axes, None, '', major=major)
  42. def get_view_interval(self):
  43. return self.axes.upper_xlim[0], self.axes.lower_xlim[1]
  44. # This class exists to calculate the separate data range of the
  45. # upper X-axis and draw the spine there. It also provides this range
  46. # to the X-axis artist for ticking and gridlines
  47. class SkewSpine(mspines.Spine):
  48. def _adjust_location(self):
  49. pts = self._path.vertices
  50. if self.spine_type == 'top':
  51. pts[:, 0] = self.axes.upper_xlim
  52. else:
  53. pts[:, 0] = self.axes.lower_xlim
  54. # This class handles registration of the skew-xaxes as a projection as well
  55. # as setting up the appropriate transformations. It also overrides standard
  56. # spines and axes instances as appropriate.
  57. class SkewXAxes(Axes):
  58. # The projection must specify a name. This will be used be the
  59. # user to select the projection, i.e. ``subplot(111,
  60. # projection='skewx')``.
  61. name = 'skewx'
  62. def _init_axis(self):
  63. # Taken from Axes and modified to use our modified X-axis
  64. self.xaxis = SkewXAxis(self)
  65. self.spines['top'].register_axis(self.xaxis)
  66. self.spines['bottom'].register_axis(self.xaxis)
  67. self.yaxis = maxis.YAxis(self)
  68. self.spines['left'].register_axis(self.yaxis)
  69. self.spines['right'].register_axis(self.yaxis)
  70. def _gen_axes_spines(self):
  71. spines = {'top': SkewSpine.linear_spine(self, 'top'),
  72. 'bottom': mspines.Spine.linear_spine(self, 'bottom'),
  73. 'left': mspines.Spine.linear_spine(self, 'left'),
  74. 'right': mspines.Spine.linear_spine(self, 'right')}
  75. return spines
  76. def _set_lim_and_transforms(self):
  77. """
  78. This is called once when the plot is created to set up all the
  79. transforms for the data, text and grids.
  80. """
  81. rot = 30
  82. # Get the standard transform setup from the Axes base class
  83. Axes._set_lim_and_transforms(self)
  84. # Need to put the skew in the middle, after the scale and limits,
  85. # but before the transAxes. This way, the skew is done in Axes
  86. # coordinates thus performing the transform around the proper origin
  87. # We keep the pre-transAxes transform around for other users, like the
  88. # spines for finding bounds
  89. self.transDataToAxes = (self.transScale +
  90. (self.transLimits +
  91. transforms.Affine2D().skew_deg(rot, 0)))
  92. # Create the full transform from Data to Pixels
  93. self.transData = self.transDataToAxes + self.transAxes
  94. # Blended transforms like this need to have the skewing applied using
  95. # both axes, in axes coords like before.
  96. self._xaxis_transform = (transforms.blended_transform_factory(
  97. self.transScale + self.transLimits,
  98. transforms.IdentityTransform()) +
  99. transforms.Affine2D().skew_deg(rot, 0)) + self.transAxes
  100. @property
  101. def lower_xlim(self):
  102. return self.axes.viewLim.intervalx
  103. @property
  104. def upper_xlim(self):
  105. pts = [[0., 1.], [1., 1.]]
  106. return self.transDataToAxes.inverted().transform(pts)[:, 0]
  107. # Now register the projection with matplotlib so the user can select
  108. # it.
  109. register_projection(SkewXAxes)
  110. @image_comparison(['skew_axes'], remove_text=True)
  111. def test_set_line_coll_dash_image():
  112. fig = plt.figure()
  113. ax = fig.add_subplot(1, 1, 1, projection='skewx')
  114. ax.set_xlim(-50, 50)
  115. ax.set_ylim(50, -50)
  116. ax.grid(True)
  117. # An example of a slanted line at constant X
  118. ax.axvline(0, color='b')
  119. @image_comparison(['skew_rects'], remove_text=True)
  120. def test_skew_rectangle():
  121. fix, axes = plt.subplots(5, 5, sharex=True, sharey=True, figsize=(8, 8))
  122. axes = axes.flat
  123. rotations = list(itertools.product([-3, -1, 0, 1, 3], repeat=2))
  124. axes[0].set_xlim([-3, 3])
  125. axes[0].set_ylim([-3, 3])
  126. axes[0].set_aspect('equal', share=True)
  127. for ax, (xrots, yrots) in zip(axes, rotations):
  128. xdeg, ydeg = 45 * xrots, 45 * yrots
  129. t = transforms.Affine2D().skew_deg(xdeg, ydeg)
  130. ax.set_title('Skew of {0} in X and {1} in Y'.format(xdeg, ydeg))
  131. ax.add_patch(mpatch.Rectangle([-1, -1], 2, 2,
  132. transform=t + ax.transData,
  133. alpha=0.5, facecolor='coral'))
  134. plt.subplots_adjust(wspace=0, left=0.01, right=0.99, bottom=0.01, top=0.99)