This question already has answers here:
Which is the recommended way to plot: matplotlib or pylab?
(2 answers)
Closed 1 year ago.
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?
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.
Related
I'm reading the documentation for matplotlib. Under the 'Coding Styles' section, it says:
When viewing this documentation and examples, you will find different coding styles and usage patterns.
Later...
Of the different styles, there are two that are officially supported. Therefore, these are the preferred ways to use matplotlib.
For the pyplot style...
But then in the rest of that section they never explicitly explain or mention the 'second' supported coding style. They say something about a 'MATLAB-style' but it is unclear from the context if that is referring to the pyplot style (as if it is like MATLAB) or if it is a separate style itself.
Question
What is the second supported matplotlib coding style and how does it relate / differ from the pyplot style?
Arguably this part of the usage guide is a bit hard to understand in its current form. There was however an update recently (#14223), which might make it clearer. A preview version of this can be found here:
https://matplotlib.org/devdocs/tutorials/introductory/usage.html#the-object-oriented-interface-and-the-pyplot-interface
As noted above, there are essentially two ways to use Matplotlib:
Explicitly create figures and axes, and call methods on them (the "object-oriented (OO) style").
Rely on pyplot to automatically create and manage the figures and axes, and use pyplot functions for plotting.
The next level down in the hierarchy is the first level of the object-oriented
interface, in which pyplot is used only for a few functions such as figure
creation, and the user explicitly creates and keeps track of the figure and axes
objects. At this level, the user uses pyplot to create figures, and through those
figures, one or more axes objects can be created. These axes objects are then used
for most plotting actions.
I'm not really new to matplotlib and I'm deeply ashamed to admit I have always used it as a tool for getting a solution as quick and easy as possible. So I know how to get basic plots, subplots and stuff and have quite a few code which gets reused from time to time...but I have no "deep(er) knowledge" of matplotlib.
Recently I thought I should change this and work myself through some tutorials. However, I am still confused about matplotlibs plt, fig(ure) and ax(arr). What is really the difference?
In most cases, for some "quick'n'dirty' plotting I see people using just pyplot as plt and directly plot with plt.plot. Since I am having multiple stuff to plot quite often, I frequently use f, axarr = plt.subplots()...but most times you see only code putting data into the axarr and ignoring the figure f.
So, my question is: what is a clean way to work with matplotlib? When to use plt only, what is or what should a figure be used for? Should subplots just containing data? Or is it valid and good practice to everything like styling, clearing a plot, ..., inside of subplots?
I hope this is not to wide-ranging. Basically I am asking for some advice for the true purposes of plt <-> fig <-> ax(arr) (and when/how to use them properly).
Tutorials would also be welcome. The matplotlib documentation is rather confusing to me. When one searches something really specific, like rescaling a legend, different plot markers and colors and so on the official documentation is really precise but rather general information is not that good in my opinion. Too much different examples, no real explanations of the purposes...looks more or less like a big listing of all possible API methods and arguments.
pyplot is the 'scripting' level API in matplotlib (its highest level API to do a lot with matplotlib). It allows you to use matplotlib using a procedural interface in a similar way as you can do it with Matlab. pyplot has a notion of 'current figure' and 'current axes' that all the functions delegate to (#tacaswell dixit). So, when you use the functions available on the module pyplot you are plotting to the 'current figure' and 'current axes'.
If you want 'fine-grain' control of where/what your are plotting then you should use an object oriented API using instances of Figure and Axes.
Functions available in pyplot have an equivalent method in the Axes.
From the repo anatomy of matplotlib:
The Figure is the top-level container in this hierarchy. It is the overall window/page that everything is drawn on. You can have multiple independent figures and Figures can contain multiple Axes.
But...
Most plotting occurs on an Axes. The axes is effectively the area that we plot data on and any ticks/labels/etc associated with it. Usually we'll set up an Axes with a call to subplot (which places Axes on a regular grid), so in most cases, Axes and Subplot are synonymous.
Each Axes has an XAxis and a YAxis. These contain the ticks, tick locations, labels, etc.
If you want to know the anatomy of a plot you can visit this link.
I think that this tutorial explains well the basic notions of the object hierarchy of matplotlib like Figure and Axes, as well as the notion of current figure and current Axes.
If you want a quick answer: There is the Figure object which is the container that wraps multiple Axes(which is different from axis) which also contains smaller objects like legends, line, tick marks ... as shown in this image taken from matplotlib documentation
So when we do
>>> import matplotlib.pyplot as plt
>>> fig, ax = plt.subplots()
>>> type(fig)
<class 'matplotlib.figure.Figure'>
>>> type(ax)
<class 'matplotlib.axes._subplots.AxesSubplot'>
We have created a Figure object and an Axes object that is contained in that figure.
pyplot is matlab like API for those who are familiar with matlab and want to make quick and dirty plots
figure is object-oriented API for those who doesn't care about matlab style plotting
So you can use either one but perhaps not both together.
I hope this question isn't too elementary. I've searched extensively for a solution but haven't discovered one yet.
I've recently begun using Jupyter Notebook with Sympy to take notes and do my homework in my Calculus II class (and what a HUGE BENEFIT this has been!).
However, my sole problem with it is that I'm unable to figure out how to configure the size (i.e. the dimensions in pixels) of the plot figure.
It's easy enough to do using matplotlib directly (matplotlib.pyplot.figure() specifically), but I'm using the Sympy.mpmath.plotmodule because Sympy works much better for the symbolic manipulation we're doing in this course. I know Sympy has its own plotting module, but the one in mpmath seems easier to use so far (with the exception of this one issue, of course).
However, I've looked through the mpmath documentation and have googled the problem repeatedly, without a solution.
How can you change the size of the image that results from plotting a function using the mpmath API?
You may try changing the size of sympy's plots via pyplot's rcParams:
import sympy
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams['figure.figsize'] = 10, 3
sympy.mpmath.plot([cos, sin], [-4, 4])
I visited the scipy site for PyLab. I could not find its documentation there. The matplotlib site also does not provide any information on it.
Where can I find a tutorial/documentation on PyLab?
Pylab is basically just Numpy and Matplotlib under a unified namespace. Learn about either of those and you will understand Pylab.
If you want to plot things in scripts it is generally preferred that you use import matplotlib.pyplot instead of import pylab, but really the choice is up to you.
If you want to have interactive plotting (for instance, by calling ipython --pylab) then pylab is the way to go. However pyplot can also be put in an interactive mode using pyplot.ion().
Some more information can be found here:
What is the difference between pylab and pyplot?
Exact semantics of Matplotlib's "interactive mode" (ion(), ioff())?
I am trying to understand how methods and attributes are organized in matplotlib. For example, say I have a figure:
import matplotlib.pyplot as plt
my_fig = plt.imshow(image)
I have noticed that some figure properties are set via module methods, e.g.:
plt.axis('off')
while others are set for the figure itself using object methods:
my_fig.set_cmap('hot')
Can figure properties be specified in either way?
How can I turn off the axis by calling methods on my object my_fig?
The plt methods are part of the pyplot API, which is intended to provide Matlab-like convenience for interactive use (and certainly appears to be very influenced by Matlab). But it's just one small facet of the whole matplotlib API (which is much more OOP). In practice I seem to end up mixing them both myself in SW; it's largely a matter of taste whether you go through the pyplot API or access the objects. pyplot is certainly very convenient although as you want to do more complex/exotic things you'll find what you can do with pyplot alone limited and you'll need to get to know at least the full API's Axes, Figure, Legend and Path objects better.
Pyplot is a collection of command style functions that make matplotlib work like MATLAB, matplotlib.figure.Figure is part of the object-oriented API.
In most cases you can configure figure settings via itself like this:
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
image=mpimg.imread('stinkbug.png')
my_fig = plt.imshow(image)
my_fig.axes.axes.get_xaxis().set_visible(False)
my_fig.axes.axes.get_yaxis().set_visible(False)
plt.show()
enter code here
required stinkbug.png:
result: