12
12
"""
13
13
14
14
from collections import OrderedDict
15
+ import dateutil .parser
15
16
import itertools
17
+ import logging
16
18
17
19
import numpy as np
18
20
21
+ import matplotlib .cbook as cbook
19
22
import matplotlib .units as units
20
23
import matplotlib .ticker as ticker
21
24
22
25
26
+ _log = logging .getLogger (__name__ )
27
+
28
+
23
29
class StrCategoryConverter (units .ConversionInterface ):
24
30
@staticmethod
25
31
def convert (value , unit , axis ):
@@ -174,6 +180,21 @@ def __init__(self, data=None):
174
180
if data is not None :
175
181
self .update (data )
176
182
183
+ @staticmethod
184
+ def _str_is_convertible (val ):
185
+ """
186
+ Helper method to see if a string can be cast to float or
187
+ parsed as date.
188
+ """
189
+ try :
190
+ float (val )
191
+ except ValueError :
192
+ try :
193
+ dateutil .parser .parse (val )
194
+ except ValueError :
195
+ return False
196
+ return True
197
+
177
198
def update (self , data ):
178
199
"""Maps new values to integer identifiers.
179
200
@@ -189,11 +210,22 @@ def update(self, data):
189
210
"""
190
211
data = np .atleast_1d (np .array (data , dtype = object ))
191
212
213
+ # check if convertable to number:
214
+ convertable = True
192
215
for val in OrderedDict .fromkeys (data ):
216
+ # OrderedDict just iterates over unique values in data.
193
217
if not isinstance (val , (str , bytes )):
194
218
raise TypeError ("{val!r} is not a string" .format (val = val ))
219
+ if convertable :
220
+ # this will only be called so long as convertable is True.
221
+ convertable = self ._str_is_convertible (val )
195
222
if val not in self ._mapping :
196
223
self ._mapping [val ] = next (self ._counter )
224
+ if convertable :
225
+ _log .info ('Using categorical units to plot a list of strings '
226
+ 'that are all parsable as floats or dates. If these '
227
+ 'strings should be plotted as numbers, cast to the '
228
+ 'approriate data type before plotting.' )
197
229
198
230
199
231
# Register the converter with Matplotlib's unit framework
0 commit comments