4

I imported matplotlib in the way like this:

import matplotlib as mpl

A error saying 'module' object has no attribute 'pylab' was thrown out when i run the following code:

x = np.arange(0,10,0.01)   # import numpy as np
y = np.sin(x)
mpl.pylab.plot(x,y)
mpl.pylab.show()

And there was no error appears when i imported matplotlib in another way:

import matplotlib.pylab as pl

Is there anybody knows what happend?

3 Answers 3

10

To plot in non-interactive mode, you should use the module pyplot, not pylab.

from matplotlib import pyplot
import numpy

pyplot.plot(range(1,100), numpy.sin(range(1,100)))
pyplot.show()

The module pylab is not typically used as a submodule of matplotlib, but as a top-level module instead. Typically, it is used in interactive mode to bring together several parts of numpy, scipy and matplotlib into one namespace.

>>> from pylab import *
>>> plot(range(1,100), sin(range(1,100)))
>>> show()
Sign up to request clarification or add additional context in comments.

2 Comments

I care nothing but how to use pylab or pyplot correctly! BUT what you mentioned it's a good advice to me.
@ Chinmay: from pyplot import * has to be pylab, I think
5

Submodules are not always imported by default. You can import pylab with

import matplotlib as mpl
import matplotlib.pylab  # Loads the pylab submodule as well
# mpl.pylab is now defined

This is why doing import matplotlib.pylab as pl solved the problem, for you.

Not importing submodules by default brings faster loading times. It also does not pollute the main module namespace with unused submodule names. The creator of a module can define which submodules are loaded by default (since pylab is quite heavy, it is not imported by default by matplotlib).

Comments

-1

You normally get this error if the module you are trying to import does not have a __init__.py file. I also get this error on my installation. I think you just have to accept that you must import matplotlib.pylab separately from matplotlib.

1 Comment

Which submodules are imported by default is actually under the full control of the module creator. In the case of pylab, matplotlib/__init__.py could in fact include a simple import pylab and matplotlib.pylab would be made available through import matplotlib (there is no need for it to have an __init__.py file).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.