Skip to content

plt.errorbar raises error when given marker=<matplotlib.markers.MarkerStyle object> #18600

Closed

Description

@evanberkowitz

Bug report

Bug summary

plt.errorbar( ..., marker=<matplotlib.markers.MarkerStyle object>) raises a `TypeError: float() argument must be a string or a number, not 'MarkerStyle' unexpectedly.

Code for reproduction

#!/usr/bin/env python3

import matplotlib
import matplotlib.pyplot as plt
from matplotlib.markers import MarkerStyle

print(f"{matplotlib.__version__=}")
print(matplotlib.get_backend())

# I want to use this marker in an errorbar plot
m = MarkerStyle("D")
m._transform.scale(1.0, 0.6)
print(m)

# I can use it in a scatter plot
fig, ax = plt.subplots()
plt.scatter([1,2,3],[1,2,3], s=225, marker="d")
plt.scatter([1,2,3],[2,3,4], s=225, marker=m, color="crimson")
plt.errorbar([1,2,3],[3,4,5], yerr=[0.5,0.5,0.5], marker='o', linestyle='none', color='green')
plt.show()
# which produces a figure similar to https://stackoverflow.com/a/49662571/

# But when I use it in errorbar
fix, ax = plt.subplots()
plt.errorbar([1,2,3],[3,4,5], yerr=[0.5,0.5,0.5], marker=m, linestyle='none', color='green')
plt.show()

Actual outcome

The first figure is produced with a correctly-rotated marker, similar to this Stack Overflow answer, which looks like this:

Figure_1

After closing the first figure, the second figure, in contrast, gives an error.

> ./example.py
matplotlib.__version__='3.2.2'
<matplotlib.markers.MarkerStyle object at 0x106e89d00>
Traceback (most recent call last):
  File "./example.py", line 25, in <module>
    plt.errorbar([1,2,3],[3,4,5], yerr=[0.5,0.5,0.5], marker=m, color='green')
  File "/usr/local/lib/python3.8/site-packages/matplotlib/pyplot.py", line 2524, in errorbar
    return gca().errorbar(
  File "/usr/local/lib/python3.8/site-packages/matplotlib/__init__.py", line 1565, in inner
    return func(ax, *map(sanitize_sequence, args), **kwargs)
  File "/usr/local/lib/python3.8/site-packages/matplotlib/axes/_axes.py", line 3265, in errorbar
    data_line = mlines.Line2D(x, y, **plot_line_style)
  File "/usr/local/lib/python3.8/site-packages/matplotlib/lines.py", line 378, in __init__
    self._marker = MarkerStyle(marker, fillstyle)
  File "/usr/local/lib/python3.8/site-packages/matplotlib/markers.py", line 225, in __init__
    self.set_marker(marker)
  File "/usr/local/lib/python3.8/site-packages/matplotlib/markers.py", line 289, in set_marker
    Path(marker)
  File "/usr/local/lib/python3.8/site-packages/matplotlib/path.py", line 127, in __init__
    vertices = _to_unmasked_float_array(vertices)
  File "/usr/local/lib/python3.8/site-packages/matplotlib/cbook/__init__.py", line 1317, in _to_unmasked_float_array
    return np.asarray(x, float)
  File "/usr/local/lib/python3.8/site-packages/numpy/core/_asarray.py", line 83, in asarray
    return array(a, dtype, copy=False, order=order)
TypeError: float() argument must be a string or a number, not 'MarkerStyle'

Expected outcome

The second figure should show a sequence of diamonds that are the thin_diamond marker but rotated 90˚ (so that it's wider than it is tall), like the red diamonds in the first figure, but with error bars of width 0.5 (like the green circles in the first figure).

Matplotlib version

  • Operating system: macOS Catalina 10.15.6
  • Matplotlib version: 3.2.2
  • Matplotlib backend (print(matplotlib.get_backend())): MacOSX
  • Python version: 3.8.5
  • Jupyter version (if applicable):
  • Other libraries:

Installed mpl via pip3.

Activity

  1. changed the title [-]plt.errorbar raises error when given `marker=<matplotlib.markers.MarkerStyle object>`[/-] [+]plt.errorbar raises error when given marker=<matplotlib.markers.MarkerStyle object>[/+] on Sep 28, 2020
  2. evanberkowitz commented on Sep 28, 2020

    @evanberkowitz
    ContributorAuthor

    A temporary workaround is to scatter with the marker and errorbar with marker=None.

    Even with this workaround, however, my manual construction of a legend fails. For my 'real' example (non minimal-working-example) I need to construct a legend manually.

    In the script below when WORKAROUND_PROBLEM=True the legend construction fails, when it is False the original problem is demonstrated.

    #!/usr/bin/env python3
    
    import matplotlib
    import matplotlib.pyplot as plt
    from matplotlib.markers import MarkerStyle
    
    print(f"{matplotlib.__version__=}")
    print(f"{matplotlib.get_backend()=}")
    
    # I want to use this marker in an errorbar plot
    m = MarkerStyle("D")
    m._transform.scale(1.0, 0.6)
    print(m)
    
    # I can use it in a scatter plot
    fig, ax = plt.subplots()
    plt.scatter([1,2,3],[1,2,3], s=225, marker="d")
    plt.scatter([1,2,3],[2,3,4], s=225, marker=m, color="crimson")
    plt.errorbar([1,2,3],[3,4,5], yerr=[0.5,0.5,0.5], marker='o', linestyle='none', color='green')
    plt.show()
    # which produces a figure similar to https://stackoverflow.com/a/49662571/
    
    # Workaround:
    fig, ax = plt.subplots()
    plt.scatter([1,2,3],[3,4,5], marker=m, color='green', label='wide diamond')
    plt.errorbar([1,2,3],[3,4,5], yerr=[0.5,0.5,0.5], marker=None, linestyle='none', color='green')
    plt.legend()
    plt.show()
    
    WORKAROUND_PROBLEM=True
    
    if WORKAROUND_PROBLEM:
        fig, ax = plt.subplots()
        plt.scatter([1,2,3],[3,4,5], marker=m, color='green')
        plt.errorbar([1,2,3],[3,4,5], yerr=[0.5,0.5,0.5], marker=None, linestyle='none', color='green')
        # A manual legend construction:
        import matplotlib.lines as mlines
        legend = [mlines.Line2D([],[], color='green', marker=m, label='wide diamond', linestyle='none', fillstyle='none', markersize=12)]
        plt.legend(handles=legend)
        plt.show()
    
    else:
        # But when I use it in errorbar
        fix, ax = plt.subplots()
        plt.errorbar([1,2,3],[3,4,5], yerr=[0.5,0.5,0.5], marker=m, linestyle='none', color='green')
        plt.show()

    The result of the legend version of the problem is

    > ./example.py
    matplotlib.__version__='3.2.2'
    matplotlib.get_backend()='MacOSX'
    <matplotlib.markers.MarkerStyle object at 0x1006edd00>
    Traceback (most recent call last):
      File "./example.py", line 38, in <module>
        legend = [mlines.Line2D([],[], color='green', marker=m, label='wide diamond', linestyle='none', fillstyle='none', markersize=12)]
      File "/usr/local/lib/python3.8/site-packages/matplotlib/lines.py", line 378, in __init__
        self._marker = MarkerStyle(marker, fillstyle)
      File "/usr/local/lib/python3.8/site-packages/matplotlib/markers.py", line 225, in __init__
        self.set_marker(marker)
      File "/usr/local/lib/python3.8/site-packages/matplotlib/markers.py", line 289, in set_marker
        Path(marker)
      File "/usr/local/lib/python3.8/site-packages/matplotlib/path.py", line 127, in __init__
        vertices = _to_unmasked_float_array(vertices)
      File "/usr/local/lib/python3.8/site-packages/matplotlib/cbook/__init__.py", line 1317, in _to_unmasked_float_array
        return np.asarray(x, float)
      File "/usr/local/lib/python3.8/site-packages/numpy/core/_asarray.py", line 83, in asarray
        return array(a, dtype, copy=False, order=order)
    TypeError: float() argument must be a string or a number, not 'MarkerStyle'
    

    The expected outcome is that the figure on which the legend is failing should look like the second figure (scatter+errorbar with the legend given by a label).

  3. jklymak commented on Sep 28, 2020

    @jklymak
    Member

    Someone simply forgot to add that functionality to errorbar. Probably an easy enough fix?

  4. evanberkowitz commented on Sep 28, 2020

    @evanberkowitz
    ContributorAuthor

    I hope so! The tracebacks of both the errorbar and legend work-around share some common lines---there might be a place 'upstream' to make this fix?

  5. evanberkowitz commented on Sep 28, 2020

    @evanberkowitz
    ContributorAuthor

    @jklymak Can you point me in the right direction (maybe to a specific file?) where I can compare errorbar and scatter? I tried grepping around but didn't find anything obvious...

  6. QuLogic commented on Sep 28, 2020

    @QuLogic
    Member

    errorbar and scatter are defined in lib/matplotlib/axes/_axes.py

  7. evanberkowitz commented on Sep 28, 2020

    @evanberkowitz
    ContributorAuthor

    OK, now that I have a virtual development environment set up (having followed these instructions), the behavior is different!

    I removed the workaround part of my script---here's what I'm currently testing:

    #!/usr/bin/env python3
    
    import matplotlib
    import matplotlib.pyplot as plt
    from matplotlib.markers import MarkerStyle
    
    print(f"{matplotlib.__version__=}")
    print(f"{matplotlib.get_backend()=}")
    
    # I want to use this marker in an errorbar plot
    m = MarkerStyle("d")
    m._transform.rotate_deg(90)
    print(m)
    
    # I can use it in a scatter plot
    fig, ax = plt.subplots()
    plt.scatter([1,2,3],[1,2,3], s=225, marker="d", label='thin diamond')
    plt.scatter([1,2,3],[2,3,4], s=225, marker=m, color="crimson", label='wide diamond')
    plt.errorbar([1,2,3],[3,4,5], yerr=[0.5,0.5,0.5], marker='o', linestyle='none', color='green', label='error bar')
    plt.legend()
    plt.show()
    # which produces a figure similar to https://stackoverflow.com/a/49662571/
    
    # But when I use it in errorbar
    fix, ax = plt.subplots()
    plt.errorbar([1,2,3],[3,4,5], yerr=[0.5,0.5,0.5], marker=m, linestyle='none', color='green')
    import matplotlib.lines as mlines
    legend = [mlines.Line2D([],[], color='green', marker=m, label='wide diamond', linestyle='none', fillstyle='none', markersize=12)]
    plt.legend(handles=legend)
    plt.show()

    I changed how I was getting my new marker by rotating 'd' rather than scaling 'D'.

    The first figure remains the same (OK, I added a legend in the upper left using the built-in label=... and plt.legend()---the legend shows the wide diamond correctly)

    The second figure now plots the markers in the body of the figure correctly but the marker does not show correctly in the legend---it isn't wider than it is tall / rotated! Instead, it's taller than it is wide (like the usual 'd').

    Figure_1

    When I run I now get no exceptions

    > ./example.py
    matplotlib.__version__='3.3.2.post1182+gf9d291895'
    matplotlib.get_backend()='MacOSX'
    <matplotlib.markers.MarkerStyle object at 0x107e70d60>
    

    [exit 0]

  8. QuLogic commented on Sep 28, 2020

    @QuLogic
    Member

    I think the original issue would have been fixed by #17930, because marker is now passed through the normal process that would happen via plot. If there's something wrong with the legends, it's probably in legend_handler.py.

    That being said, I'm not sure modifying a private attribute like _transform is a supported approach. This may or may not be okay if you subclass it instead.

  9. evanberkowitz commented on Sep 29, 2020

    @evanberkowitz
    ContributorAuthor

    @QuLogic indeed---you're right. I think that the problem is that when legline_marker is constructed and its properties update_proped, the marker isn't truly copied---I think the new one is built from the string from the old one (in this case 'd'). Inserting

      242         legline_marker = Line2D(xdata_marker, ydata[:len(xdata_marker)])
      243         self.update_prop(legline_marker, orig_handle, legend)
    + 244         legline_marker.set_marker(orig_handle.__dict__['_marker'])

    to (losslessly?) copy accomplishes what I need (but, as you point out, is not generic). If the marker copy was deep, there would be no problem. But I have found myself down a rabbit's hole of HandlerBase's update_prop, _update_prop, _default_update_prop and the link. I believe I wind up at line 70 of legend_hanlder.py,

       69     def _default_update_prop(self, legend_handle, orig_handle):
       70         legend_handle.update_from(orig_handle)

    at which point I do not understand what happens---legend handlers do not seem to have an update_from (and neither do HandlerLine2D or HandlerBase inheirit from Artist (which does have such a method).

    Obviously my little hack (line 244 above) is not a permanent solution. How do you suggest I proceed?

    Figure_1

  10. evanberkowitz commented on Sep 29, 2020

    @evanberkowitz
    ContributorAuthor

    I see---the legend_handle is a Line2D, not a legend handler! My issue seems to stem from the fact that in Line2D's update_from method, the marker isn't copied so much as it is reconstructed:

      1301         self._linestyle = other._linestyle
      1302         self._marker = MarkerStyle(other._marker.get_marker(),
      1303                                    other._marker.get_fillstyle())

    while almost every other property is copied in the self = other way, Markers are reconstructed from the get_marker() and get_fillstyle(). I see that these lines have been this way since 2011---is there a good reason to not just copy but to reconstruct the marker?

  11. evanberkowitz commented on Sep 29, 2020

    @evanberkowitz
    ContributorAuthor

    With my #18603 I get a figure identical to my hacky solution of 2 comments ago.

  12. added this to the v3.4.0 milestone on Oct 2, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions