Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1""" 

2The classes here provide support for using custom classes with 

3Matplotlib, e.g., those that do not expose the array interface but know 

4how to convert themselves to arrays. It also supports classes with 

5units and units conversion. Use cases include converters for custom 

6objects, e.g., a list of datetime objects, as well as for objects that 

7are unit aware. We don't assume any particular units implementation; 

8rather a units implementation must provide the register with the Registry 

9converter dictionary and a `ConversionInterface`. For example, 

10here is a complete implementation which supports plotting with native 

11datetime objects:: 

12 

13 import matplotlib.units as units 

14 import matplotlib.dates as dates 

15 import matplotlib.ticker as ticker 

16 import datetime 

17 

18 class DateConverter(units.ConversionInterface): 

19 

20 @staticmethod 

21 def convert(value, unit, axis): 

22 'Convert a datetime value to a scalar or array' 

23 return dates.date2num(value) 

24 

25 @staticmethod 

26 def axisinfo(unit, axis): 

27 'Return major and minor tick locators and formatters' 

28 if unit!='date': return None 

29 majloc = dates.AutoDateLocator() 

30 majfmt = dates.AutoDateFormatter(majloc) 

31 return AxisInfo(majloc=majloc, 

32 majfmt=majfmt, 

33 label='date') 

34 

35 @staticmethod 

36 def default_units(x, axis): 

37 'Return the default unit for x or None' 

38 return 'date' 

39 

40 # Finally we register our object type with the Matplotlib units registry. 

41 units.registry[datetime.date] = DateConverter() 

42 

43""" 

44 

45from decimal import Decimal 

46from numbers import Number 

47 

48import numpy as np 

49from numpy import ma 

50 

51from matplotlib import cbook 

52 

53 

54class ConversionError(TypeError): 

55 pass 

56 

57 

58def _is_natively_supported(x): 

59 """ 

60 Return whether *x* is of a type that Matplotlib natively supports or an 

61 array of objects of such types. 

62 """ 

63 # Matplotlib natively supports all number types except Decimal. 

64 if np.iterable(x): 

65 # Assume lists are homogeneous as other functions in unit system. 

66 for thisx in x: 

67 if thisx is ma.masked: 

68 continue 

69 return isinstance(thisx, Number) and not isinstance(thisx, Decimal) 

70 else: 

71 return isinstance(x, Number) and not isinstance(x, Decimal) 

72 

73 

74class AxisInfo: 

75 """ 

76 Information to support default axis labeling, tick labeling, and limits. 

77 

78 An instance of this class must be returned by 

79 `ConversionInterface.axisinfo`. 

80 """ 

81 def __init__(self, majloc=None, minloc=None, 

82 majfmt=None, minfmt=None, label=None, 

83 default_limits=None): 

84 """ 

85 Parameters 

86 ---------- 

87 majloc, minloc : Locator, optional 

88 Tick locators for the major and minor ticks. 

89 majfmt, minfmt : Formatter, optional 

90 Tick formatters for the major and minor ticks. 

91 label : str, optional 

92 The default axis label. 

93 default_limits : optional 

94 The default min and max limits of the axis if no data has 

95 been plotted. 

96 

97 Notes 

98 ----- 

99 If any of the above are ``None``, the axis will simply use the 

100 default value. 

101 """ 

102 self.majloc = majloc 

103 self.minloc = minloc 

104 self.majfmt = majfmt 

105 self.minfmt = minfmt 

106 self.label = label 

107 self.default_limits = default_limits 

108 

109 

110class ConversionInterface: 

111 """ 

112 The minimal interface for a converter to take custom data types (or 

113 sequences) and convert them to values Matplotlib can use. 

114 """ 

115 

116 @staticmethod 

117 def axisinfo(unit, axis): 

118 """ 

119 Return an `~units.AxisInfo` for the axis with the specified units. 

120 """ 

121 return None 

122 

123 @staticmethod 

124 def default_units(x, axis): 

125 """ 

126 Return the default unit for *x* or ``None`` for the given axis. 

127 """ 

128 return None 

129 

130 @staticmethod 

131 def convert(obj, unit, axis): 

132 """ 

133 Convert *obj* using *unit* for the specified *axis*. 

134 

135 If *obj* is a sequence, return the converted sequence. The output must 

136 be a sequence of scalars that can be used by the numpy array layer. 

137 """ 

138 return obj 

139 

140 @staticmethod 

141 def is_numlike(x): 

142 """ 

143 The Matplotlib datalim, autoscaling, locators etc work with scalars 

144 which are the units converted to floats given the current unit. The 

145 converter may be passed these floats, or arrays of them, even when 

146 units are set. 

147 """ 

148 if np.iterable(x): 

149 for thisx in x: 

150 if thisx is ma.masked: 

151 continue 

152 return isinstance(thisx, Number) 

153 else: 

154 return isinstance(x, Number) 

155 

156 

157class DecimalConverter(ConversionInterface): 

158 """ 

159 Converter for decimal.Decimal data to float. 

160 """ 

161 @staticmethod 

162 def convert(value, unit, axis): 

163 """ 

164 Convert Decimals to floats. 

165 

166 The *unit* and *axis* arguments are not used. 

167 

168 Parameters 

169 ---------- 

170 value : decimal.Decimal or iterable 

171 Decimal or list of Decimal need to be converted 

172 """ 

173 # If value is a Decimal 

174 if isinstance(value, Decimal): 

175 return np.float(value) 

176 else: 

177 # assume x is a list of Decimal 

178 converter = np.asarray 

179 if isinstance(value, ma.MaskedArray): 

180 converter = ma.asarray 

181 return converter(value, dtype=np.float) 

182 

183 @staticmethod 

184 def axisinfo(unit, axis): 

185 # Since Decimal is a kind of Number, don't need specific axisinfo. 

186 return AxisInfo() 

187 

188 @staticmethod 

189 def default_units(x, axis): 

190 # Return None since Decimal is a kind of Number. 

191 return None 

192 

193 

194class Registry(dict): 

195 """Register types with conversion interface.""" 

196 

197 def get_converter(self, x): 

198 """Get the converter interface instance for *x*, or None.""" 

199 if hasattr(x, "values"): 

200 x = x.values # Unpack pandas Series and DataFrames. 

201 if isinstance(x, np.ndarray): 

202 # In case x in a masked array, access the underlying data (only its 

203 # type matters). If x is a regular ndarray, getdata() just returns 

204 # the array itself. 

205 x = np.ma.getdata(x).ravel() 

206 # If there are no elements in x, infer the units from its dtype 

207 if not x.size: 

208 return self.get_converter(np.array([0], dtype=x.dtype)) 

209 for cls in type(x).__mro__: # Look up in the cache. 

210 try: 

211 return self[cls] 

212 except KeyError: 

213 pass 

214 try: # If cache lookup fails, look up based on first element... 

215 first = cbook.safe_first_element(x) 

216 except (TypeError, StopIteration): 

217 pass 

218 else: 

219 # ... and avoid infinite recursion for pathological iterables for 

220 # which indexing returns instances of the same iterable class. 

221 if type(first) is not type(x): 

222 return self.get_converter(first) 

223 return None 

224 

225 

226registry = Registry() 

227registry[Decimal] = DecimalConverter()