16

I usually use the following package to create my plots: matplotlib.pylab. However, there is also a package called matplotlib.pyplot.

I have not been able to spot any difference between the two when using them. So my question is the following:

What is the difference between the packages matplotlib.pylab and matplotlib.pyplot. In which cases would you advice one over the other?

3

1 Answer 1

14

Per the FAQ:

Pyplot provides the state-machine interface to the underlying plotting library in matplotlib. This means that figures and axes are implicitly and automatically created to achieve the desired plot....

Pylab combines the pyplot functionality (for plotting) with the numpy functionality (for mathematics and for working with arrays) in a single namespace, making that namespace (or environment) even more MATLAB-like. For example, one can call the sin and cos functions just like you could in MATLAB, as well as having all the features of pyplot.

The pyplot interface is generally preferred for non-interactive plotting (i.e., scripting). The pylab interface is convenient for interactive calculations and plotting, as it minimizes typing. (my emphasis.)

Note that

from pylab import *

also performs

from numpy import *

This overwrites many builtin Python functions such as:

In [5]: import __builtin__
In [6]: import numpy as np

In [5]: {name for name in set(dir(np)).intersection(dir(__builtin__)) if not name.startswith('__') and getattr(__builtin__, name) != getattr(np, name)}
Out[5]: {'abs', 'all', 'any', 'max', 'min', 'round', 'sum'}

Therefore, I don't like from pylab import * (or really from module import * for any module) because it makes well-known beloved Python names behave in unexpected ways (if you do not always keep in mind that from numpy import * has polluted the global namespace.)

For example,

In [32]: np.all([np.arange(3), np.arange(3)])
Out[32]: False

while

In [33]: all([np.arange(3), np.arange(3)])
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Sign up to request clarification or add additional context in comments.

Comments

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.