From c9a0ac725336a544eb89a749e727cf0a604446b9 Mon Sep 17 00:00:00 2001 From: Tim Hoffmann <2836374+timhoffm@users.noreply.github.com> Date: Mon, 17 Dec 2018 16:44:24 +0100 Subject: [PATCH] Improve error messages for unit conversion --- lib/matplotlib/axis.py | 7 +++++-- lib/matplotlib/category.py | 26 ++++++++++++++++---------- lib/matplotlib/units.py | 4 ++++ 3 files changed, 25 insertions(+), 12 deletions(-) diff --git a/lib/matplotlib/axis.py b/lib/matplotlib/axis.py index 31ec36f8e86e..fccd473210a5 100644 --- a/lib/matplotlib/axis.py +++ b/lib/matplotlib/axis.py @@ -1486,8 +1486,11 @@ def convert_units(self, x): if self.converter is None: return x - - ret = self.converter.convert(x, self.units, self) + try: + ret = self.converter.convert(x, self.units, self) + except Exception as e: + raise munits.ConversionError('Failed to convert value(s) to axis ' + f'units: {x!r}') from e return ret def set_units(self, u): diff --git a/lib/matplotlib/category.py b/lib/matplotlib/category.py index 9eeb686276d6..e755bfed0330 100644 --- a/lib/matplotlib/category.py +++ b/lib/matplotlib/category.py @@ -23,24 +23,30 @@ class StrCategoryConverter(units.ConversionInterface): @staticmethod def convert(value, unit, axis): - """Converts strings in value to floats using + """Convert strings in value to floats using mapping information store in the unit object. Parameters ---------- value : string or iterable - value or list of values to be converted - unit : :class:`.UnitData` - object string unit information for value - axis : :class:`~matplotlib.Axis.axis` - axis on which the converted value is plotted + Value or list of values to be converted. + unit : `.UnitData` + An object mapping strings to integers. + axis : `~matplotlib.axis.Axis` + axis on which the converted value is plotted. + + .. note:: *axis* is unused. Returns ------- - mapped_ value : float or ndarray[float] - - .. note:: axis is not used in this function + mapped_value : float or ndarray[float] """ + if unit is None: + raise ValueError( + 'Missing category information for StrCategoryConverter; ' + 'this might be caused by unintendedly mixing categorical and ' + 'numeric data') + # dtype = object preserves numerical pass throughs values = np.atleast_1d(np.array(value, dtype=object)) @@ -190,7 +196,7 @@ def update(self, data): self._mapping[val] = next(self._counter) -# Connects the convertor to matplotlib +# Register the converter with Matplotlib's unit framework units.registry[str] = StrCategoryConverter() units.registry[np.str_] = StrCategoryConverter() units.registry[bytes] = StrCategoryConverter() diff --git a/lib/matplotlib/units.py b/lib/matplotlib/units.py index adfa771d4190..de40d7915d4d 100644 --- a/lib/matplotlib/units.py +++ b/lib/matplotlib/units.py @@ -49,6 +49,10 @@ def default_units(x, axis): from matplotlib import cbook +class ConversionError(TypeError): + pass + + class AxisInfo(object): """ Information to support default axis labeling, tick labeling, and