8000 MNT: add a logging call if a categorical string array is all convertible by jklymak · Pull Request #13026 · matplotlib/matplotlib · GitHub
[go: up one dir, main page]

Skip to content

MNT: add a logging call if a categorical string array is all convertible #13026

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jan 20, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions lib/matplotlib/category.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,20 @@
"""

from collections import OrderedDict
import dateutil.parser
import itertools
import logging

import numpy as np

import matplotlib.cbook as cbook
import matplotlib.units as units
import matplotlib.ticker as ticker


_log = logging.getLogger(__name__)


class StrCategoryConverter(units.ConversionInterface):
@staticmethod
def convert(value, unit, axis):
Expand Down Expand Up @@ -174,6 +180,21 @@ def __init__(self, data=None):
if data is not None:
self.update(data)

@staticmethod
def _str_is_convertible(val):
"""
Helper method to see if a string can be cast to float or
parsed as date.
"""
try:
float(val)
except ValueError:
try:
dateutil.parser.parse(val)
except ValueError:
return False
return True

def update(self, data):
"""Maps new values to integer identifiers.

Expand All @@ -189,11 +210,22 @@ def update(self, data):
"""
data = np.atleast_1d(np.array(data, dtype=object))

# check if convertable to number:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

arriving after the battle, but this should have been named "convertible", not "convertable"...

convertable = True
for val in OrderedDict.fromkeys(data):
# OrderedDict just iterates over unique values in data.
if not isinstance(val, (str, bytes)):
raise TypeError("{val!r} is not a string".format(val=val))
if convertable:
# this will only be called so long as convertable is True.
convertable = self._str_is_convertible(val)
if val not in self._mapping:
self._mapping[val] = next(self._counter)
if convertable:
_log.info('Using categorical units to plot a list of strings '
'that are all parsable as floats or dates. If these '
'strings should be plotted as numbers, cast to the '
'approriate data type before plotting.')


# Register the converter with Matplotlib's unit framework
Expand Down
0