Skip to content

Plotting with Matplotlib from Pandas #1917

@icarosadero

Description

@icarosadero
pint version: 0.23
pandas version: 2.1.4
pint_pandas version: 0.5

The expected behavior is to have matplot be able to make a scatter plot from a pandas DataFrame.

Minimal example:

import pandas as pd
import pint
import pint_pandas

ureg = pint.UnitRegistry()
ureg.setup_matplotlib(True)

du = pd.DataFrame({
    "torque": pd.Series([1, 2, 2, 3], dtype="pint[lbf ft]"),
    "angular_velocity": pd.Series([1, 2, 2, 3], dtype="pint[rpm]"),
})

plt.scatter(du.torque, du.angular_velocity)

Error:

---------------------------------------------------------------------------
DimensionalityError                       Traceback (most recent call last)
File $HOME/.venv/lib/python3.10/site-packages/pint/facets/plain/quantity.py:588, in PlainQuantity.__float__(self)
    587     return float(self._convert_magnitude_not_inplace(UnitsContainer()))
--> 588 raise DimensionalityError(self._units, "dimensionless")

DimensionalityError: Cannot convert from 'foot * force_pound' to 'dimensionless'

The above exception was the direct cause of the following exception:

ValueError                                Traceback (most recent call last)
Cell In[25], line 1
----> 1 plt.scatter(du.torque, du.angular_velocity)

File $HOME/.venv/lib/python3.10/site-packages/matplotlib/pyplot.py:2862, in scatter(x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, edgecolors, plotnonfinite, data, **kwargs)
   2857 @_copy_docstring_and_deprecators(Axes.scatter)
   2858 def scatter(
   2859         x, y, s=None, c=None, marker=None, cmap=None, norm=None,
   2860         vmin=None, vmax=None, alpha=None, linewidths=None, *,
   2861         edgecolors=None, plotnonfinite=False, data=None, **kwargs):
-> 2862     __ret = gca().scatter(
   2863         x, y, s=s, c=c, marker=marker, cmap=cmap, norm=norm,
   2864         vmin=vmin, vmax=vmax, alpha=alpha, linewidths=linewidths,
   2865         edgecolors=edgecolors, plotnonfinite=plotnonfinite,
   2866         **({"data": data} if data is not None else {}), **kwargs)
   2867     sci(__ret)
   2868     return __ret

File $HOME/.venv/lib/python3.10/site-packages/matplotlib/__init__.py:1446, in _preprocess_data.<locals>.inner(ax, data, *args, **kwargs)
   1443 @functools.wraps(func)
   1444 def inner(ax, *args, data=None, **kwargs):
   1445     if data is None:
-> 1446         return func(ax, *map(sanitize_sequence, args), **kwargs)
   1448     bound = new_sig.bind(ax, *args, **kwargs)
   1449     auto_label = (bound.arguments.get(label_namer)
   1450                   or bound.kwargs.get(label_namer))

File $HOME/.venv/lib/python3.10/site-packages/matplotlib/axes/_axes.py:4667, in Axes.scatter(self, x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, edgecolors, plotnonfinite, **kwargs)
   4661         linewidths = [
   4662             lw if lw is not None else mpl.rcParams['lines.linewidth']
   4663             for lw in linewidths]
   4665 offsets = np.ma.column_stack([x, y])
-> 4667 collection = mcoll.PathCollection(
   4668     (path,), scales,
   4669     facecolors=colors,
   4670     edgecolors=edgecolors,
   4671     linewidths=linewidths,
   4672     offsets=offsets,
   4673     offset_transform=kwargs.pop('transform', self.transData),
   4674     alpha=alpha,
   4675 )
   4676 collection.set_transform(mtransforms.IdentityTransform())
   4677 if colors is None:

File $HOME/.venv/lib/python3.10/site-packages/matplotlib/collections.py:994, in PathCollection.__init__(self, paths, sizes, **kwargs)
    980 def __init__(self, paths, sizes=None, **kwargs):
    981     """
    982     Parameters
    983     ----------
   (...)
    991         Forwarded to `.Collection`.
    992     """
--> 994     super().__init__(**kwargs)
    995     self.set_paths(paths)
    996     self.set_sizes(sizes)

File $HOME/.venv/lib/python3.10/site-packages/matplotlib/_api/deprecation.py:454, in make_keyword_only.<locals>.wrapper(*args, **kwargs)
    448 if len(args) > name_idx:
    449     warn_deprecated(
    450         since, message="Passing the %(name)s %(obj_type)s "
    451         "positionally is deprecated since Matplotlib %(since)s; the "
    452         "parameter will become keyword-only %(removal)s.",
    453         name=name, obj_type=f"parameter of {func.__name__}()")
--> 454 return func(*args, **kwargs)

File $HOME/.venv/lib/python3.10/site-packages/matplotlib/collections.py:192, in Collection.__init__(self, edgecolors, facecolors, linewidths, linestyles, capstyle, joinstyle, antialiaseds, offsets, offset_transform, norm, cmap, pickradius, hatch, urls, zorder, **kwargs)
    189     self._joinstyle = None
    191 if offsets is not None:
--> 192     offsets = np.asanyarray(offsets, float)
    193     # Broadcast (2,) -> (1, 2) but nothing else.
    194     if offsets.shape == (2,):

ValueError: setting an array element with a sequence.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions