Home > other >  Unhashable type 'np.ndarray' in matplotlib 3d stem example from documentation
Unhashable type 'np.ndarray' in matplotlib 3d stem example from documentation

Time:02-14

The matplotlib documentation contains the following code sample

import matplotlib.pyplot as plt
import numpy as np

theta = np.linspace(0, 2*np.pi)
x = np.cos(theta - np.pi/2)
y = np.sin(theta - np.pi/2)
z = theta

fig, ax = plt.subplots(subplot_kw=dict(projection='3d'))
ax.stem(x, y, z)

plt.show()

However, when I copy and paste this into a juypter notebook, I get an error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-42-b5d3d05087f2> in <module>
      8 
      9 fig, ax = plt.subplots(subplot_kw=dict(projection='3d'))
---> 10 ax.stem(x, y, z)
     11 
     12 plt.show()

C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\__init__.py in inner(ax, data, *args, **kwargs)
   1445     def inner(ax, *args, data=None, **kwargs):
   1446         if data is None:
-> 1447             return func(ax, *map(sanitize_sequence, args), **kwargs)
   1448 
   1449         bound = new_sig.bind(ax, *args, **kwargs)

C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\axes\_axes.py in stem(self, linefmt, markerfmt, basefmt, bottom, label, use_line_collection, *args)
   2812             else:
   2813                 linestyle, linemarker, linecolor = \
-> 2814                     _process_plot_format(linefmt)
   2815         else:
   2816             linestyle, linemarker, linecolor = _process_plot_format(linefmt)

C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\axes\_base.py in _process_plot_format(fmt)
    130     while i < len(fmt):
    131         c = fmt[i]
--> 132         if fmt[i:i 2] in mlines.lineStyles:  # First, the two-char styles.
    133             if linestyle is not None:
    134                 raise ValueError(

TypeError: unhashable type: 'numpy.ndarray'

I suspect there's something wrong with my python kernel, rather than the matplotlib documentation, but I can't figure it out. Any help would be appreciated.

Numpy version: 1.19.5

Matplotlib version: 3.3.4

CodePudding user response:

Like many matplotlib functions that accept multiple inputs, stem wants the multiple inputs as a sequence. So:

ax.stem( [x,y,z] )

What you're doing specifies x as the input, y as the line styles, and z as the marker format. Thus, when it went to look up the line styles, it was the wrong kind of structure.

99.99% of the time when you start thinking it's a bug in Python, you're wrong.

CodePudding user response:

After changing to the following module versions, the code sample from matplotlib's documentation works as intended.

Numpy version: 1.21.5

Matplotlib version: 3.5.0

  • Related