Skip to content
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

Plotting with Matplotlib from Pandas #1917

Closed
icarosadero opened this issue Jan 10, 2024 · 3 comments · May be fixed by #1931
Closed

Plotting with Matplotlib from Pandas #1917

icarosadero opened this issue Jan 10, 2024 · 3 comments · May be fixed by #1931

Comments

@icarosadero
Copy link

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.
@andrewgsavage
Copy link
Collaborator

the ureg you ran ureg.setup_matplotlib(True) is not the ureg used by pint-pandas.

do

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

or

pint_pandas.PintType.ureg.setup_matplotlib()

https://pint-pandas.readthedocs.io/en/latest/user/reading.html

@hgrecco
Copy link
Owner

hgrecco commented Jan 13, 2024

Shall we change all documentation to always get the application library? Shall we make better API that is no way to use in a wrong way?

@andrewgsavage
Copy link
Collaborator

yea good idea, that would help

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants