units.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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 register with the Registry converter
  9. dictionary and provide 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':
  25. return None
  26. majloc = dates.AutoDateLocator()
  27. majfmt = dates.AutoDateFormatter(majloc)
  28. return units.AxisInfo(majloc=majloc, majfmt=majfmt, label='date')
  29. @staticmethod
  30. def default_units(x, axis):
  31. "Return the default unit for x or None."
  32. return 'date'
  33. # Finally we register our object type with the Matplotlib units registry.
  34. units.registry[datetime.date] = DateConverter()
  35. """
  36. from decimal import Decimal
  37. from numbers import Number
  38. import numpy as np
  39. from numpy import ma
  40. from matplotlib import cbook
  41. class ConversionError(TypeError):
  42. pass
  43. def _is_natively_supported(x):
  44. """
  45. Return whether *x* is of a type that Matplotlib natively supports or an
  46. array of objects of such types.
  47. """
  48. # Matplotlib natively supports all number types except Decimal.
  49. if np.iterable(x):
  50. # Assume lists are homogeneous as other functions in unit system.
  51. for thisx in x:
  52. if thisx is ma.masked:
  53. continue
  54. return isinstance(thisx, Number) and not isinstance(thisx, Decimal)
  55. else:
  56. return isinstance(x, Number) and not isinstance(x, Decimal)
  57. class AxisInfo:
  58. """
  59. Information to support default axis labeling, tick labeling, and limits.
  60. An instance of this class must be returned by
  61. `ConversionInterface.axisinfo`.
  62. """
  63. def __init__(self, majloc=None, minloc=None,
  64. majfmt=None, minfmt=None, label=None,
  65. default_limits=None):
  66. """
  67. Parameters
  68. ----------
  69. majloc, minloc : Locator, optional
  70. Tick locators for the major and minor ticks.
  71. majfmt, minfmt : Formatter, optional
  72. Tick formatters for the major and minor ticks.
  73. label : str, optional
  74. The default axis label.
  75. default_limits : optional
  76. The default min and max limits of the axis if no data has
  77. been plotted.
  78. Notes
  79. -----
  80. If any of the above are ``None``, the axis will simply use the
  81. default value.
  82. """
  83. self.majloc = majloc
  84. self.minloc = minloc
  85. self.majfmt = majfmt
  86. self.minfmt = minfmt
  87. self.label = label
  88. self.default_limits = default_limits
  89. class ConversionInterface:
  90. """
  91. The minimal interface for a converter to take custom data types (or
  92. sequences) and convert them to values Matplotlib can use.
  93. """
  94. @staticmethod
  95. def axisinfo(unit, axis):
  96. """Return an `.AxisInfo` for the axis with the specified units."""
  97. return None
  98. @staticmethod
  99. def default_units(x, axis):
  100. """Return the default unit for *x* or ``None`` for the given axis."""
  101. return None
  102. @staticmethod
  103. def convert(obj, unit, axis):
  104. """
  105. Convert *obj* using *unit* for the specified *axis*.
  106. If *obj* is a sequence, return the converted sequence. The output must
  107. be a sequence of scalars that can be used by the numpy array layer.
  108. """
  109. return obj
  110. class DecimalConverter(ConversionInterface):
  111. """Converter for decimal.Decimal data to float."""
  112. @staticmethod
  113. def convert(value, unit, axis):
  114. """
  115. Convert Decimals to floats.
  116. The *unit* and *axis* arguments are not used.
  117. Parameters
  118. ----------
  119. value : decimal.Decimal or iterable
  120. Decimal or list of Decimal need to be converted
  121. """
  122. if isinstance(value, Decimal):
  123. return float(value)
  124. # value is Iterable[Decimal]
  125. elif isinstance(value, ma.MaskedArray):
  126. return ma.asarray(value, dtype=float)
  127. else:
  128. return np.asarray(value, dtype=float)
  129. # axisinfo and default_units can be inherited as Decimals are Numbers.
  130. class Registry(dict):
  131. """Register types with conversion interface."""
  132. def get_converter(self, x):
  133. """Get the converter interface instance for *x*, or None."""
  134. # Unpack in case of e.g. Pandas or xarray object
  135. x = cbook._unpack_to_numpy(x)
  136. if isinstance(x, np.ndarray):
  137. # In case x in a masked array, access the underlying data (only its
  138. # type matters). If x is a regular ndarray, getdata() just returns
  139. # the array itself.
  140. x = np.ma.getdata(x).ravel()
  141. # If there are no elements in x, infer the units from its dtype
  142. if not x.size:
  143. return self.get_converter(np.array([0], dtype=x.dtype))
  144. for cls in type(x).__mro__: # Look up in the cache.
  145. try:
  146. return self[cls]
  147. except KeyError:
  148. pass
  149. try: # If cache lookup fails, look up based on first element...
  150. first = cbook._safe_first_finite(x)
  151. except (TypeError, StopIteration):
  152. pass
  153. else:
  154. # ... and avoid infinite recursion for pathological iterables for
  155. # which indexing returns instances of the same iterable class.
  156. if type(first) is not type(x):
  157. return self.get_converter(first)
  158. return None
  159. registry = Registry()
  160. registry[Decimal] = DecimalConverter()