You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

199 lines
6.5 KiB

4 years ago
  1. """
  2. The classes here provide support for using custom classes with
  3. Matplotlib, e.g., those that do not expose the array interface but know
  4. how to convert themselves to arrays. It also supports classes with
  5. units and units conversion. Use cases include converters for custom
  6. objects, e.g., a list of datetime objects, as well as for objects that
  7. are unit aware. We don't assume any particular units implementation;
  8. rather a units implementation must provide the register with the Registry
  9. converter dictionary and a `ConversionInterface`. For example,
  10. here is a complete implementation which supports plotting with native
  11. datetime objects::
  12. import matplotlib.units as units
  13. import matplotlib.dates as dates
  14. import matplotlib.ticker as ticker
  15. import datetime
  16. class DateConverter(units.ConversionInterface):
  17. @staticmethod
  18. def convert(value, unit, axis):
  19. 'Convert a datetime value to a scalar or array'
  20. return dates.date2num(value)
  21. @staticmethod
  22. def axisinfo(unit, axis):
  23. 'Return major and minor tick locators and formatters'
  24. if unit!='date': return None
  25. majloc = dates.AutoDateLocator()
  26. majfmt = dates.AutoDateFormatter(majloc)
  27. return AxisInfo(majloc=majloc,
  28. majfmt=majfmt,
  29. label='date')
  30. @staticmethod
  31. def default_units(x, axis):
  32. 'Return the default unit for x or None'
  33. return 'date'
  34. # Finally we register our object type with the Matplotlib units registry.
  35. units.registry[datetime.date] = DateConverter()
  36. """
  37. from numbers import Number
  38. import numpy as np
  39. from matplotlib.cbook import iterable, safe_first_element
  40. class AxisInfo(object):
  41. """
  42. Information to support default axis labeling, tick labeling, and
  43. default limits. An instance of this class must be returned by
  44. :meth:`ConversionInterface.axisinfo`.
  45. """
  46. def __init__(self, majloc=None, minloc=None,
  47. majfmt=None, minfmt=None, label=None,
  48. default_limits=None):
  49. """
  50. Parameters
  51. ----------
  52. majloc, minloc : Locator, optional
  53. Tick locators for the major and minor ticks.
  54. majfmt, minfmt : Formatter, optional
  55. Tick formatters for the major and minor ticks.
  56. label : str, optional
  57. The default axis label.
  58. default_limits : optional
  59. The default min and max limits of the axis if no data has
  60. been plotted.
  61. Notes
  62. -----
  63. If any of the above are ``None``, the axis will simply use the
  64. default value.
  65. """
  66. self.majloc = majloc
  67. self.minloc = minloc
  68. self.majfmt = majfmt
  69. self.minfmt = minfmt
  70. self.label = label
  71. self.default_limits = default_limits
  72. class ConversionInterface(object):
  73. """
  74. The minimal interface for a converter to take custom data types (or
  75. sequences) and convert them to values Matplotlib can use.
  76. """
  77. @staticmethod
  78. def axisinfo(unit, axis):
  79. """
  80. Return an `~units.AxisInfo` instance for the axis with the
  81. specified units.
  82. """
  83. return None
  84. @staticmethod
  85. def default_units(x, axis):
  86. """
  87. Return the default unit for *x* or ``None`` for the given axis.
  88. """
  89. return None
  90. @staticmethod
  91. def convert(obj, unit, axis):
  92. """
  93. Convert *obj* using *unit* for the specified *axis*.
  94. If *obj* is a sequence, return the converted sequence.
  95. The output must be a sequence of scalars that can be used by the numpy
  96. array layer.
  97. """
  98. return obj
  99. @staticmethod
  100. def is_numlike(x):
  101. """
  102. The Matplotlib datalim, autoscaling, locators etc work with
  103. scalars which are the units converted to floats given the
  104. current unit. The converter may be passed these floats, or
  105. arrays of them, even when units are set.
  106. """
  107. if iterable(x):
  108. for thisx in x:
  109. return isinstance(thisx, Number)
  110. else:
  111. return isinstance(x, Number)
  112. class Registry(dict):
  113. """
  114. A register that maps types to conversion interfaces.
  115. """
  116. def __init__(self):
  117. dict.__init__(self)
  118. self._cached = {}
  119. def get_converter(self, x):
  120. """
  121. Get the converter for data that has the same type as *x*. If no
  122. converters are registered for *x*, returns ``None``.
  123. """
  124. if not len(self):
  125. return None # nothing registered
  126. # DISABLED idx = id(x)
  127. # DISABLED cached = self._cached.get(idx)
  128. # DISABLED if cached is not None: return cached
  129. converter = None
  130. classx = getattr(x, '__class__', None)
  131. if classx is not None:
  132. converter = self.get(classx)
  133. if converter is None and hasattr(x, "values"):
  134. # this unpacks pandas series or dataframes...
  135. x = x.values
  136. # If x is an array, look inside the array for data with units
  137. if isinstance(x, np.ndarray) and x.size:
  138. xravel = x.ravel()
  139. try:
  140. # pass the first value of x that is not masked back to
  141. # get_converter
  142. if not np.all(xravel.mask):
  143. # some elements are not masked
  144. converter = self.get_converter(
  145. xravel[np.argmin(xravel.mask)])
  146. return converter
  147. except AttributeError:
  148. # not a masked_array
  149. # Make sure we don't recurse forever -- it's possible for
  150. # ndarray subclasses to continue to return subclasses and
  151. # not ever return a non-subclass for a single element.
  152. next_item = xravel[0]
  153. if (not isinstance(next_item, np.ndarray) or
  154. next_item.shape != x.shape):
  155. converter = self.get_converter(next_item)
  156. return converter
  157. # If we haven't found a converter yet, try to get the first element
  158. if converter is None:
  159. try:
  160. thisx = safe_first_element(x)
  161. except (TypeError, StopIteration):
  162. pass
  163. else:
  164. if classx and classx != getattr(thisx, '__class__', None):
  165. converter = self.get_converter(thisx)
  166. return converter
  167. # DISABLED self._cached[idx] = converter
  168. return converter
  169. registry = Registry()