Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Error when using quantities when plotting errorbars #8871

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

Closed
bdelwood opened this issue Jul 13, 2017 · 6 comments
Closed

Error when using quantities when plotting errorbars #8871

bdelwood opened this issue Jul 13, 2017 · 6 comments

Comments

@bdelwood
Copy link

bdelwood commented Jul 13, 2017

Bug report

Bug summary

I am plotting something that requires the use of standard error. I would like to keep all my arrays as Quantities arrays (using astropy quantities in this case). However, when giving yerr an array with dimensions, an exception is thrown.

Code for reproduction

import astropy.units as u
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 10)
y = np.sin(x*np.pi)
yerr = np.random.rand(10)

x_sec = x*u.second
y_meter = y*u.meter
yerr_meter = yerr*u.meter

fig = plt.figure()
ax = fig.add_subplot(111)
ax.errorbar(x_sec, y_meter, yerr_meter)
fig.show()

Actual outcome
image

Expected outcome

It is expected that errorbar would plot the points with errorbars using quantity arrays the same as regular arrays. When yerr is taken out, the quantities plot fine. Simply using yerr_meter.value does not work, as this throws an exception related to subtracting two different quantities (y_meter and yerr). I would rather not have to call .value on all the arguments.

This appears to be related to an issue raised in astropy:
astropy/astropy#3914

Matplotlib version

  • Operating System: Windows 10, Scientific Linux 7.2
  • Matplotlib Version: 2.0.2
  • Python Version: 2.7.12
  • Other Libraries: numpy 1.12.1, astropy 1.3.2
@dstansby
Copy link
Member

dstansby commented Feb 2, 2018

This will be fixed by a combination of astropy/astropy#7037 and #10206

@dstansby dstansby added this to the v2.2 milestone Feb 2, 2018
@dstansby
Copy link
Member

Closing as fixed; this now works with Matplotlib >= 2.2, and Astropy 2.0.6 or Astropy 3.1 (not yet released)

@vuillaut
Copy link

Hi
Is this really solved? Or did another issue appear?
I copied the proposed code of the first issue.

astropy v4.1
matplotlib v3.1.3

import astropy
import matplotlib
import astropy.units as u
import matplotlib.pyplot as plt
import numpy as np

print(astropy.__version__)
print(matplotlib.__version__)

x = np.linspace(0, 10, 10)
y = np.sin(x*np.pi)
yerr = np.random.rand(10)

x_sec = x*u.second
y_meter = y*u.meter
yerr_meter = yerr*u.meter

fig = plt.figure()
ax = fig.add_subplot(111)
ax.errorbar(x_sec, y_meter, yerr_meter)
fig.show()

Output

4.1
3.1.2
---------------------------------------------------------------------------
UnitConversionError                       Traceback (most recent call last)
~/opt/anaconda3/envs/py37/lib/python3.7/site-packages/astropy/units/quantity.py in to_value(self, unit, equivalencies)
    726             try:
--> 727                 scale = self.unit._to(unit)
    728             except Exception:

~/opt/anaconda3/envs/py37/lib/python3.7/site-packages/astropy/units/core.py in _to(self, other)
    950         raise UnitConversionError(
--> 951             f"'{self!r}' is not a scaled version of '{other!r}'")
    952

UnitConversionError: 'Unit("s")' is not a scaled version of 'Unit(dimensionless)'

During handling of the above exception, another exception occurred:

UnitConversionError                       Traceback (most recent call last)
~/opt/anaconda3/envs/py37/lib/python3.7/site-packages/astropy/units/quantity.py in __float__(self)
   1072         try:
-> 1073             return float(self.to_value(dimensionless_unscaled))
   1074         except (UnitsError, TypeError):

~/opt/anaconda3/envs/py37/lib/python3.7/site-packages/astropy/units/quantity.py in to_value(self, unit, equivalencies)
    729                 # Short-cut failed; try default (maybe equivalencies help).
--> 730                 value = self._to_value(unit, equivalencies)
    731             else:

~/opt/anaconda3/envs/py37/lib/python3.7/site-packages/astropy/units/quantity.py in _to_value(self, unit, equivalencies)
    660         return self.unit.to(unit, self.view(np.ndarray),
--> 661                             equivalencies=equivalencies)
    662

~/opt/anaconda3/envs/py37/lib/python3.7/site-packages/astropy/units/core.py in to(self, other, value, equivalencies)
    986         else:
--> 987             return self._get_converter(other, equivalencies=equivalencies)(value)
    988

~/opt/anaconda3/envs/py37/lib/python3.7/site-packages/astropy/units/core.py in _get_converter(self, other, equivalencies)
    917
--> 918             raise exc
    919

~/opt/anaconda3/envs/py37/lib/python3.7/site-packages/astropy/units/core.py in _get_converter(self, other, equivalencies)
    903             return self._apply_equivalencies(
--> 904                 self, other, self._normalize_equivalencies(equivalencies))
    905         except UnitsError as exc:

~/opt/anaconda3/envs/py37/lib/python3.7/site-packages/astropy/units/core.py in _apply_equivalencies(self, unit, other, equivalencies)
    887             "{} and {} are not convertible".format(
--> 888                 unit_str, other_str))
    889

UnitConversionError: 's' (time) and '' (dimensionless) are not convertible

During handling of the above exception, another exception occurred:

TypeError                                 Traceback (most recent call last)
<ipython-input-2-14fda73d0486> in <module>
     18 fig = plt.figure()
     19 ax = fig.add_subplot(111)
---> 20 ax.errorbar(x_sec, y_meter, yerr_meter)
     21 fig.show()

~/opt/anaconda3/envs/py37/lib/python3.7/site-packages/matplotlib/__init__.py in inner(ax, data, *args, **kwargs)
   1597     def inner(ax, *args, data=None, **kwargs):
   1598         if data is None:
-> 1599             return func(ax, *map(sanitize_sequence, args), **kwargs)
   1600
   1601         bound = new_sig.bind(ax, *args, **kwargs)

~/opt/anaconda3/envs/py37/lib/python3.7/site-packages/matplotlib/axes/_axes.py in errorbar(self, x, y, yerr, xerr, fmt, ecolor, elinewidth, capsize, barsabove, lolims, uplims, xlolims, xuplims, errorevery, capthick, **kwargs)
   3428                 xo, _ = xywhere(x, lower, noylims & everymask)
   3429                 lo, uo = xywhere(lower, upper, noylims & everymask)
-> 3430                 barcols.append(self.vlines(xo, lo, uo, **eb_lines_style))
   3431                 if capsize > 0:
   3432                     caplines.append(mlines.Line2D(xo, lo, marker='_',

~/opt/anaconda3/envs/py37/lib/python3.7/site-packages/matplotlib/__init__.py in inner(ax, data, *args, **kwargs)
   1597     def inner(ax, *args, data=None, **kwargs):
   1598         if data is None:
-> 1599             return func(ax, *map(sanitize_sequence, args), **kwargs)
   1600
   1601         bound = new_sig.bind(ax, *args, **kwargs)

~/opt/anaconda3/envs/py37/lib/python3.7/site-packages/matplotlib/axes/_axes.py in vlines(self, x, ymin, ymax, colors, linestyles, label, **kwargs)
   1185             ymax = [ymax]
   1186
-> 1187         x, ymin, ymax = cbook.delete_masked_points(x, ymin, ymax)
   1188
   1189         x = np.ravel(x)

~/opt/anaconda3/envs/py37/lib/python3.7/site-packages/matplotlib/cbook/__init__.py in delete_masked_points(*args)
   1042                     raise ValueError("Masked arrays must be 1-D")
   1043             else:
-> 1044                 x = np.asarray(x)
   1045         margs.append(x)
   1046     masks = []    # list of masks that are True where good

~/opt/anaconda3/envs/py37/lib/python3.7/site-packages/numpy/core/_asarray.py in asarray(a, dtype, order)
     81
     82     """
---> 83     return array(a, dtype, copy=False, order=order)
     84
     85

~/opt/anaconda3/envs/py37/lib/python3.7/site-packages/astropy/units/quantity.py in __float__(self)
   1073             return float(self.to_value(dimensionless_unscaled))
   1074         except (UnitsError, TypeError):
-> 1075             raise TypeError('only dimensionless scalar quantities can be '
   1076                             'converted to Python scalars')
   1077

TypeError: only dimensionless scalar quantities can be converted to Python scalars

@Lachimax
Copy link

I have the same error as above, running matplotlib 3.3.4 and astropy 4.2.1.

@jklymak
Copy link
Member

jklymak commented May 30, 2021

Please try latest matplotlib. If this is still an issue please open a new issue. Thanks!

@jklymak
Copy link
Member

jklymak commented May 30, 2021

This works fine with 3.4.2 and astropy 4.3.dev, so I don't think there is anything to do here.

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

No branches or pull requests

7 participants