hanachronism
hanachronism

Reputation: 761

matplotlib has no attribute 'pyplot'

I can import matplotlib but when I try to run the following:

matplotlib.pyplot(x)

I get:

Traceback (most recent call last):
   File "<pyshell#31>", line 1, in <module>
       matplotlib.pyplot(x)
AttributeError: 'module' object has no attribute 'pyplot'

Upvotes: 65

Views: 187548

Answers (3)

mgilson
mgilson

Reputation: 310287

pyplot is a submodule of matplotlib, but it doesn't get imported with import matplotlib only:

>>> import matplotlib
>>> matplotlib.pyplot
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'pyplot'
>>> import matplotlib.pyplot
>>> 

However, it is recommended to alias it as plt:

import matplotlib.pyplot as plt

Then, you can use the various functions and classes it contains:

p = plt.plot(...)

Upvotes: 62

Sarkis Bouzikian
Sarkis Bouzikian

Reputation: 3

simple answer worked for me if you are importing 'librosa' library, just import it before 'import matplotlib.pyplot as plt'. That worked for me and couple others for similar issue

Upvotes: 0

Thorsten Kranz
Thorsten Kranz

Reputation: 12765

Did you import it? Importing matplotlib is not enough.

>>> import matplotlib
>>> matplotlib.pyplot
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'pyplot'

but

>>> import matplotlib.pyplot
>>> matplotlib.pyplot

works.

pyplot is a submodule of matplotlib and not immediately imported when you import matplotlib.

The most common form of importing pyplot is

import matplotlib.pyplot as plt

Thus, your statements won't be too long, e.g.

plt.plot([1,2,3,4,5])

instead of

matplotlib.pyplot.plot([1,2,3,4,5])

And: pyplot is not a function, it's a module! So don't call it, use the functions defined inside this module instead. See my example above

Upvotes: 44

Related Questions