自定义比例尺

通过在墨卡托投影中实现纬度数据的缩放用途来创建自定义比例。

自定义比例尺示例

  1. import numpy as np
  2. from numpy import ma
  3. from matplotlib import scale as mscale
  4. from matplotlib import transforms as mtransforms
  5. from matplotlib.ticker import Formatter, FixedLocator
  6. from matplotlib import rcParams
  7. # BUG: this example fails with any other setting of axisbelow
  8. rcParams['axes.axisbelow'] = False
  9. class MercatorLatitudeScale(mscale.ScaleBase):
  10. """
  11. Scales data in range -pi/2 to pi/2 (-90 to 90 degrees) using
  12. the system used to scale latitudes in a Mercator projection.
  13. The scale function:
  14. ln(tan(y) + sec(y))
  15. The inverse scale function:
  16. atan(sinh(y))
  17. Since the Mercator scale tends to infinity at +/- 90 degrees,
  18. there is user-defined threshold, above and below which nothing
  19. will be plotted. This defaults to +/- 85 degrees.
  20. source:
  21. http://en.wikipedia.org/wiki/Mercator_projection
  22. """
  23. # The scale class must have a member ``name`` that defines the
  24. # string used to select the scale. For example,
  25. # ``gca().set_yscale("mercator")`` would be used to select this
  26. # scale.
  27. name = 'mercator'
  28. def __init__(self, axis, *, thresh=np.deg2rad(85), **kwargs):
  29. """
  30. Any keyword arguments passed to ``set_xscale`` and
  31. ``set_yscale`` will be passed along to the scale's
  32. constructor.
  33. thresh: The degree above which to crop the data.
  34. """
  35. mscale.ScaleBase.__init__(self)
  36. if thresh >= np.pi / 2:
  37. raise ValueError("thresh must be less than pi/2")
  38. self.thresh = thresh
  39. def get_transform(self):
  40. """
  41. Override this method to return a new instance that does the
  42. actual transformation of the data.
  43. The MercatorLatitudeTransform class is defined below as a
  44. nested class of this one.
  45. """
  46. return self.MercatorLatitudeTransform(self.thresh)
  47. def set_default_locators_and_formatters(self, axis):
  48. """
  49. Override to set up the locators and formatters to use with the
  50. scale. This is only required if the scale requires custom
  51. locators and formatters. Writing custom locators and
  52. formatters is rather outside the scope of this example, but
  53. there are many helpful examples in ``ticker.py``.
  54. In our case, the Mercator example uses a fixed locator from
  55. -90 to 90 degrees and a custom formatter class to put convert
  56. the radians to degrees and put a degree symbol after the
  57. value::
  58. """
  59. class DegreeFormatter(Formatter):
  60. def __call__(self, x, pos=None):
  61. return "%d\N{DEGREE SIGN}" % np.degrees(x)
  62. axis.set_major_locator(FixedLocator(
  63. np.radians(np.arange(-90, 90, 10))))
  64. axis.set_major_formatter(DegreeFormatter())
  65. axis.set_minor_formatter(DegreeFormatter())
  66. def limit_range_for_scale(self, vmin, vmax, minpos):
  67. """
  68. Override to limit the bounds of the axis to the domain of the
  69. transform. In the case of Mercator, the bounds should be
  70. limited to the threshold that was passed in. Unlike the
  71. autoscaling provided by the tick locators, this range limiting
  72. will always be adhered to, whether the axis range is set
  73. manually, determined automatically or changed through panning
  74. and zooming.
  75. """
  76. return max(vmin, -self.thresh), min(vmax, self.thresh)
  77. class MercatorLatitudeTransform(mtransforms.Transform):
  78. # There are two value members that must be defined.
  79. # ``input_dims`` and ``output_dims`` specify number of input
  80. # dimensions and output dimensions to the transformation.
  81. # These are used by the transformation framework to do some
  82. # error checking and prevent incompatible transformations from
  83. # being connected together. When defining transforms for a
  84. # scale, which are, by definition, separable and have only one
  85. # dimension, these members should always be set to 1.
  86. input_dims = 1
  87. output_dims = 1
  88. is_separable = True
  89. has_inverse = True
  90. def __init__(self, thresh):
  91. mtransforms.Transform.__init__(self)
  92. self.thresh = thresh
  93. def transform_non_affine(self, a):
  94. """
  95. This transform takes an Nx1 ``numpy`` array and returns a
  96. transformed copy. Since the range of the Mercator scale
  97. is limited by the user-specified threshold, the input
  98. array must be masked to contain only valid values.
  99. ``matplotlib`` will handle masked arrays and remove the
  100. out-of-range data from the plot. Importantly, the
  101. ``transform`` method *must* return an array that is the
  102. same shape as the input array, since these values need to
  103. remain synchronized with values in the other dimension.
  104. """
  105. masked = ma.masked_where((a < -self.thresh) | (a > self.thresh), a)
  106. if masked.mask.any():
  107. return ma.log(np.abs(ma.tan(masked) + 1.0 / ma.cos(masked)))
  108. else:
  109. return np.log(np.abs(np.tan(a) + 1.0 / np.cos(a)))
  110. def inverted(self):
  111. """
  112. Override this method so matplotlib knows how to get the
  113. inverse transform for this transform.
  114. """
  115. return MercatorLatitudeScale.InvertedMercatorLatitudeTransform(
  116. self.thresh)
  117. class InvertedMercatorLatitudeTransform(mtransforms.Transform):
  118. input_dims = 1
  119. output_dims = 1
  120. is_separable = True
  121. has_inverse = True
  122. def __init__(self, thresh):
  123. mtransforms.Transform.__init__(self)
  124. self.thresh = thresh
  125. def transform_non_affine(self, a):
  126. return np.arctan(np.sinh(a))
  127. def inverted(self):
  128. return MercatorLatitudeScale.MercatorLatitudeTransform(self.thresh)
  129. # Now that the Scale class has been defined, it must be registered so
  130. # that ``matplotlib`` can find it.
  131. mscale.register_scale(MercatorLatitudeScale)
  132. if __name__ == '__main__':
  133. import matplotlib.pyplot as plt
  134. t = np.arange(-180.0, 180.0, 0.1)
  135. s = np.radians(t)/2.
  136. plt.plot(t, s, '-', lw=2)
  137. plt.gca().set_yscale('mercator')
  138. plt.xlabel('Longitude')
  139. plt.ylabel('Latitude')
  140. plt.title('Mercator: Projection of the Oppressor')
  141. plt.grid(True)
  142. plt.show()

下载这个示例