I see that I can plot in Python using either:
import matplotlib
matplotlib.pyplot.plot(...)
Or:
import pylab
pylab.plot(...)
Both of these use the same matplotlib plotting code.
So, which of these does the Python community recommend as the better method to plot? Why?
The documentation at https://matplotlib.org/faq/usage_faq.html#matplotlib-pyplot-and-pylab-how-are-they-related, which also describes the difference between pyglot and pylab, states: "Although many examples use pylab, it is no longer recommended.". So, I don't see any reason to use pylab or worry about it.
Official docs: Matplotlib, pyplot and pylab: how are they related?
Both of those imports boil down do doing exactly the same thing and will run the exact same code, it is just different ways of importing the modules.
Also note that
matplotlib
has two interface layers, a state-machine layer managed bypyplot
and the OO interfacepyplot
is built on top of, see How can I attach a pyplot function to a figure instance?pylab
is a clean way to bulk import a whole slew of helpful functions (thepyplot
state machine function, most ofnumpy
) into a single name space. The main reason this exists (to my understanding) is to work withipython
to make a very nice interactive shell which more-or-less replicates MATLAB (to make the transition easier and because it is good for playing around). Seepylab.py
andmatplotlib/pylab.py
At some level, this is purely a matter of taste and depends a bit on what you are doing.
If you are not embedding in a gui (either using a non-interactive backend for bulk scripts or using one of the provided interactive backends) the typical thing to do is
which doesn't pollute the name space. I prefer this so I can keep track of where stuff came from.
If you use
this is equivalent to running
It is now recommended that for new versions of
ipython
you usewhich will set up all the proper background details to make the interactive backends to work nicely, but will not bulk import anything. You will need to explicitly import the modules want.
is a good start.
If you are embedding
matplotlib
in a gui you don't want to import pyplot as that will start extra gui main loops, and exactly what you should import depends on exactly what you are doing.