Skip to content

[Bug]: Markers can be integers, but numpy integers fail #30836

@has2k1

Description

@has2k1

Bug summary

There are workflows where a sequence of markers could end up in a numpy array or a pandas series. If that sequence contains only integers, the marker values will become of type np.int64. It is therefore reasonable to expect that these values, different in type but equal to those in the input sequence, not lead to an error.

Code for reproduction

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

caretleft1 = [4][0]
caretleft2 = np.array([4])[0]

assert caretleft1 in MarkerStyle.markers
assert caretleft2 in MarkerStyle.markers

# plt.plot([1, 2, 3], marker=caretleft1) # works
plt.plot([1, 2, 3], marker=caretleft2) # fails

Actual outcome

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
File ~/abc/.venv/lib/python3.13/site-packages/matplotlib/markers.py:326, in MarkerStyle._set_marker(self, marker)
    325 try:
--> 326     Path(marker)
    327     self._marker_function = self._set_vertices

File ~/abc/.venv/lib/python3.13/site-packages/matplotlib/path.py:130, in Path.__init__(self, vertices, codes, _interpolation_steps, closed, readonly)
    129 vertices = _to_unmasked_float_array(vertices)
--> 130 _api.check_shape((None, 2), vertices=vertices)
    132 if codes is not None and len(vertices):

File ~/abc/.venv/lib/python3.13/site-packages/matplotlib/_api/__init__.py:162, in check_shape(shape, **kwargs)
    160     text_shape += ","
--> 162 raise ValueError(
    163     f"{k!r} must be {len(shape)}D with shape ({text_shape}), "
    164     f"but your input has shape {v.shape}"
    165 )

ValueError: 'vertices' must be 2D with shape (N, 2), but your input has shape ()

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

ValueError                                Traceback (most recent call last)
Cell In[5], line 1
----> 1 plt.plot([1, 2, 3], marker=caretleft2)

File ~/abc/.venv/lib/python3.13/site-packages/matplotlib/pyplot.py:3838, in plot(scalex, scaley, data, *args, **kwargs)
   3830 @_copy_docstring_and_deprecators(Axes.plot)
   3831 def plot(
   3832     *args: float | ArrayLike | str,
   (...)   3836     **kwargs,
   3837 ) -> list[Line2D]:
-> 3838     return gca().plot(
   3839         *args,
   3840         scalex=scalex,
   3841         scaley=scaley,
   3842         **({"data": data} if data is not None else {}),
   3843         **kwargs,
   3844     )

File ~/abc/.venv/lib/python3.13/site-packages/matplotlib/axes/_axes.py:1777, in Axes.plot(self, scalex, scaley, data, *args, **kwargs)
   1534 """
   1535 Plot y versus x as lines and/or markers.
   1536 
   (...)   1774 (``'green'``) or hex strings (``'#008000'``).
   1775 """
   1776 kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D)
-> 1777 lines = [*self._get_lines(self, *args, data=data, **kwargs)]
   1778 for line in lines:
   1779     self.add_line(line)

File ~/abc/.venv/lib/python3.13/site-packages/matplotlib/axes/_base.py:297, in _process_plot_var_args.__call__(self, axes, data, return_kwargs, *args, **kwargs)
    295     this += args[0],
    296     args = args[1:]
--> 297 yield from self._plot_args(
    298     axes, this, kwargs, ambiguous_fmt_datakey=ambiguous_fmt_datakey,
    299     return_kwargs=return_kwargs
    300 )

File ~/abc/.venv/lib/python3.13/site-packages/matplotlib/axes/_base.py:546, in _process_plot_var_args._plot_args(self, axes, tup, kwargs, return_kwargs, ambiguous_fmt_datakey)
    544     return list(result)
    545 else:
--> 546     return [l[0] for l in result]

File ~/abc/.venv/lib/python3.13/site-packages/matplotlib/axes/_base.py:539, in <genexpr>(.0)
    534 else:
    535     raise ValueError(
    536         f"label must be scalar or have the same length as the input "
    537         f"data, but found {len(label)} for {n_datasets} datasets.")
--> 539 result = (make_artist(axes, x[:, j % ncx], y[:, j % ncy], kw,
    540                       {**kwargs, 'label': label})
    541           for j, label in enumerate(labels))
    543 if return_kwargs:
    544     return list(result)

File ~/abc/.venv/lib/python3.13/site-packages/matplotlib/axes/_base.py:338, in _process_plot_var_args._make_line(self, axes, x, y, kw, kwargs)
    336 kw = {**kw, **kwargs}  # Don't modify the original kw.
    337 self._setdefaults(self._getdefaults(kw), kw)
--> 338 seg = mlines.Line2D(x, y, **kw)
    339 return seg, kw

File ~/abc/.venv/lib/python3.13/site-packages/matplotlib/lines.py:394, in Line2D.__init__(self, xdata, ydata, linewidth, linestyle, color, gapcolor, marker, markersize, markeredgewidth, markeredgecolor, markerfacecolor, markerfacecoloralt, fillstyle, antialiased, dash_capstyle, solid_capstyle, dash_joinstyle, solid_joinstyle, pickradius, drawstyle, markevery, **kwargs)
    392     marker = 'none'  # Default.
    393 if not isinstance(marker, MarkerStyle):
--> 394     self._marker = MarkerStyle(marker, fillstyle)
    395 else:
    396     self._marker = marker

File ~/abc/.venv/lib/python3.13/site-packages/matplotlib/markers.py:248, in MarkerStyle.__init__(self, marker, fillstyle, transform, capstyle, joinstyle)
    246 self._user_joinstyle = JoinStyle(joinstyle) if joinstyle is not None else None
    247 self._set_fillstyle(fillstyle)
--> 248 self._set_marker(marker)

File ~/abc/.venv/lib/python3.13/site-packages/matplotlib/markers.py:329, in MarkerStyle._set_marker(self, marker)
    327         self._marker_function = self._set_vertices
    328     except ValueError as err:
--> 329         raise ValueError(
    330             f'Unrecognized marker style {marker!r}') from err
    332 if not isinstance(marker, MarkerStyle):
    333     self._marker = marker

ValueError: Unrecognized marker style np.int64(4)

Expected outcome

Image

Additional information

I will submit a PR.

Operating system

No response

Matplotlib Version

   import matplotlib; print(matplotlib.__version__) 3.10.3

Matplotlib Backend

No response

Python version

No response

Jupyter version

No response

Installation

None

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions