FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

Error when using quantities when plotting errorbars · Issue #8871 · matplotlib/matplotlib · GitHub

Repository navigation

Error when using quantities when plotting errorbars #8871

Closed

Description

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

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

Activity

  1. dstansby commented on Feb 2, 2018

    Member

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

  2. added this to the milestone on Feb 2, 2018
  3. dstansby commented on Sep 25, 2018

    Member

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

  4. modified the milestones: needs sorting, v2.2.0 on Sep 25, 2018
  5. vuillaut commented on Nov 25, 2020

    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
    
  6. Lachimax commented on May 30, 2021

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

  7. jklymak commented on May 30, 2021

    Member

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

  8. jklymak commented on May 30, 2021

    Member

    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

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions


    Back | FazBrowse Home | New Git URL