units.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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 decimal import Decimal
  38. from numbers import Number
  39. import numpy as np
  40. from numpy import ma
  41. from matplotlib import cbook
  42. class ConversionError(TypeError):
  43. pass
  44. def _is_natively_supported(x):
  45. """
  46. Return whether *x* is of a type that Matplotlib natively supports or an
  47. array of objects of such types.
  48. """
  49. # Matplotlib natively supports all number types except Decimal.
  50. if np.iterable(x):
  51. # Assume lists are homogeneous as other functions in unit system.
  52. for thisx in x:
  53. if thisx is ma.masked:
  54. continue
  55. return isinstance(thisx, Number) and not isinstance(thisx, Decimal)
  56. else:
  57. return isinstance(x, Number) and not isinstance(x, Decimal)
  58. class AxisInfo:
  59. """
  60. Information to support default axis labeling, tick labeling, and limits.
  61. An instance of this class must be returned by
  62. `ConversionInterface.axisinfo`.
  63. """
  64. def __init__(self, majloc=None, minloc=None,
  65. majfmt=None, minfmt=None, label=None,
  66. default_limits=None):
  67. """
  68. Parameters
  69. ----------
  70. majloc, minloc : Locator, optional
  71. Tick locators for the major and minor ticks.
  72. majfmt, minfmt : Formatter, optional
  73. Tick formatters for the major and minor ticks.
  74. label : str, optional
  75. The default axis label.
  76. default_limits : optional
  77. The default min and max limits of the axis if no data has
  78. been plotted.
  79. Notes
  80. -----
  81. If any of the above are ``None``, the axis will simply use the
  82. default value.
  83. """
  84. self.majloc = majloc
  85. self.minloc = minloc
  86. self.majfmt = majfmt
  87. self.minfmt = minfmt
  88. self.label = label
  89. self.default_limits = default_limits
  90. class ConversionInterface:
  91. """
  92. The minimal interface for a converter to take custom data types (or
  93. sequences) and convert them to values Matplotlib can use.
  94. """
  95. @staticmethod
  96. def axisinfo(unit, axis):
  97. """
  98. Return an `~units.AxisInfo` for the axis with the specified units.
  99. """
  100. return None
  101. @staticmethod
  102. def default_units(x, axis):
  103. """
  104. Return the default unit for *x* or ``None`` for the given axis.
  105. """
  106. return None
  107. @staticmethod
  108. def convert(obj, unit, axis):
  109. """
  110. Convert *obj* using *unit* for the specified *axis*.
  111. If *obj* is a sequence, return the converted sequence. The output must
  112. be a sequence of scalars that can be used by the numpy array layer.
  113. """
  114. return obj
  115. @staticmethod
  116. def is_numlike(x):
  117. """
  118. The Matplotlib datalim, autoscaling, locators etc work with scalars
  119. which are the units converted to floats given the current unit. The
  120. converter may be passed these floats, or arrays of them, even when
  121. units are set.
  122. """
  123. if np.iterable(x):
  124. for thisx in x:
  125. if thisx is ma.masked:
  126. continue
  127. return isinstance(thisx, Number)
  128. else:
  129. return isinstance(x, Number)
  130. class DecimalConverter(ConversionInterface):
  131. """
  132. Converter for decimal.Decimal data to float.
  133. """
  134. @staticmethod
  135. def convert(value, unit, axis):
  136. """
  137. Convert Decimals to floats.
  138. The *unit* and *axis* arguments are not used.
  139. Parameters
  140. ----------
  141. value : decimal.Decimal or iterable
  142. Decimal or list of Decimal need to be converted
  143. """
  144. # If value is a Decimal
  145. if isinstance(value, Decimal):
  146. return np.float(value)
  147. else:
  148. # assume x is a list of Decimal
  149. converter = np.asarray
  150. if isinstance(value, ma.MaskedArray):
  151. converter = ma.asarray
  152. return converter(value, dtype=np.float)
  153. @staticmethod
  154. def axisinfo(unit, axis):
  155. # Since Decimal is a kind of Number, don't need specific axisinfo.
  156. return AxisInfo()
  157. @staticmethod
  158. def default_units(x, axis):
  159. # Return None since Decimal is a kind of Number.
  160. return None
  161. class Registry(dict):
  162. """Register types with conversion interface."""
  163. def get_converter(self, x):
  164. """Get the converter interface instance for *x*, or None."""
  165. if hasattr(x, "values"):
  166. x = x.values # Unpack pandas Series and DataFrames.
  167. if isinstance(x, np.ndarray):
  168. # In case x in a masked array, access the underlying data (only its
  169. # type matters). If x is a regular ndarray, getdata() just returns
  170. # the array itself.
  171. x = np.ma.getdata(x).ravel()
  172. # If there are no elements in x, infer the units from its dtype
  173. if not x.size:
  174. return self.get_converter(np.array([0], dtype=x.dtype))
  175. for cls in type(x).__mro__: # Look up in the cache.
  176. try:
  177. return self[cls]
  178. except KeyError:
  179. pass
  180. try: # If cache lookup fails, look up based on first element...
  181. first = cbook.safe_first_element(x)
  182. except (TypeError, StopIteration):
  183. pass
  184. else:
  185. # ... and avoid infinite recursion for pathological iterables for
  186. # which indexing returns instances of the same iterable class.
  187. if type(first) is not type(x):
  188. return self.get_converter(first)
  189. return None
  190. registry = Registry()
  191. registry[Decimal] = DecimalConverter()