diff --git a/lib/matplotlib/axis.py b/lib/matplotlib/axis.py index 06a3925dd35a..4658385ffc56 100644 --- a/lib/matplotlib/axis.py +++ b/lib/matplotlib/axis.py @@ -1526,8 +1526,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 bdc05301e5ad..74ed8137a493 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 c23d791b092a..1798f59db7dc 100644 --- a/lib/matplotlib/units.py +++ b/lib/matplotlib/units.py @@ -49,6 +49,10 @@ def default_units(x, axis): from matplotlib.cbook import iterable, safe_first_element +class ConversionError(TypeError): + pass + + class AxisInfo(object): """ Information to support default axis labeling, tick labeling, and