Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why matplotlib has no attribute 'pylab'?

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?

like image 235
YOng Avatar asked Dec 09 '22 09:12

YOng


2 Answers

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()
like image 176
Chinmay Kanchi Avatar answered Jan 22 '23 07:01

Chinmay Kanchi


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).

like image 24
Eric O Lebigot Avatar answered Jan 22 '23 07:01

Eric O Lebigot