207

What is the difference between matplotlib.pyplot and matplotlib.pylab?

Which is preferred for what usage?

I am a little confused, because it seems like independent from which I import, I can do the same things. What am I missing?

Saullo G. P. Castro
  • 56,802
  • 26
  • 179
  • 234
Claus
  • 4,409
  • 4
  • 19
  • 16
  • This question is marked as the duplicate because the other does not recommend using `pylab`, per the official documentation. See this [answer](https://stackoverflow.com/a/51011921/7758804). – Trenton McKinney May 06 '21 at 17:26

1 Answers1

172

This wording is no longer in the documentation.

Use of the pylab import is now discouraged and the OO interface is recommended for most non-interactive usage.


From the documentation, the emphasis is mine:

Matplotlib is the whole package; pylab is a module in matplotlib that gets installed alongside matplotlib; and matplotlib.pyplot is a module in matplotlib.

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. For example, calling plot from pyplot will automatically create the necessary figure and axes to achieve the desired plot. Setting a title will then automatically set that title to the current axes object:

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. Note that this is what you get if you use the ipython shell with the -pylab option, which imports everything from pylab and makes plotting fully interactive.

Community
  • 1
  • 1
Hooked
  • 84,485
  • 43
  • 192
  • 261
  • 4
    from the [matplotlib faq](http://matplotlib.org/faq/usage_faq.html#matplotlib-pyplot-and-pylab-how-are-they-related) it seems they are disfavouring pylab: "pylab is a convenience module that bulk imports matplotlib.pyplot (for plotting) and numpy (for mathematics and working with arrays) in a single name space. *Although many examples use pylab, it is no longer recommended.*" – M.T Dec 15 '15 at 13:46
  • 11
    @Reb.Cabin http://matplotlib.org/examples/api/agg_oo.html The idea behind the object oriented interface is to not use `plt.figure()` `plt.plot(x,y)`... but rather create a Figure, add an Axes to the Figure and add a plot to the Axes. It is object oriented because instead of referring to `plt.*` and let pyplot guess to what figure you are referring to, you (the developer) are responsible to refer the Figure or Axes object. – zeehio Jan 29 '16 at 17:22