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.
Related
Let me first say I've never studied matplotlib and pyplot organically. I've been able to employ these fantastic tools to some success however without developing a big picture of how things are supposed to be used. One of the thing that confuse me the most is the use of axes instances.
In many occasions I have found solutions to a particular problem which make use of axes or do not.
Example: one can set ticks to the x-axis through matplotlib.pyplot.xticks without using axes or through matplotlib.axes.Axes.set_xticks.
I usually try to avoid the use of axes. However there are times at which this seems to not be possible. For example when trying to use subplots with shared axis.
Can someone help me to shed some light on this subject? When am i supposed to use axes? When should I not?
Thanks.
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 would like to know if there is a way to combined several figures created with matplotlib in one unique figure.
Most of the existing topics are related to multiple plots within one figure. But here, I have several functions which all create one elaborated figure (not just a plot, the figure itself is a multiple plot with texts, title, legends,...)
So instead of just doing the layout of those several figures using a software like Word, is there a way to directly combined all my figures in one unique figure under python ?
Thank you in advance !
The concept of figure in matplotlib does not allow to have a figure inside a figure. The figure is the canvas for other artists, like axes. You may of course add as many axes to a figure as you like. So for example instead of one figure with 4 axes and another figure with 6 axes, you can create a figure with 10 axes.
A good choice may be to use the gridspec, as detailed on the respecive matplotlib page.
After additional researches, it seems my problem has no easy solution within Matplotlib itself. Multiple figures layout needs external post-processing of plots.
For those having the same problem, here is an interesting link :
Publication-quality figures with matplotlib and svgutils
In this period I am working with matplotlib. I studied many examples, and was able to modify it to suit several of my needs. But I would like to better understand the general structure of the library. For this reason, apart reading a lot of tutorials on the web, I also purchased the ebook "Matplotlib for Python Developers", by Tosi. While it is full of good examples, I still don't fully grasp the relationships between all the different levels.
The book clearly explains that matplotlib has 3 main "modes":
1) pylab, to work similarly to Matlab
2) pyplot, to work in a procedural way
3) the full OO system
Concerning the objects of the OO system, the book lists 3 levels:
1) FigureCanvas, the container class for the Figure instance
2) Figure, the container for Axes instances
3) Axes, the areas that hold the basic elements (lines, points, text...)
The problem is that, by reading the official documentation, I also encountered the notions of Backends and Artists. While I understand the basic logic of them, I am quite confused about their role respect to the previous classifications. In particular, are the Artists in an intermediate level between the FigureCanvas and the Figure, or is that hierarchy not suitable in this case?
I would be grateful to receive some clarifications, eventually also referring to other documentation I could have missed.
Thanks.
I do not like those layers
pylab : massive namespace dump that pulls in everything from pyplot and numpy. It is not a 'layer' so much as a very cluttered name space.
pyplot : state-machine based layer (it knows what your 'current axes' and 'current figure' are and applies the functions to that axes/figure. You should use this only when you are playing around in an interactive terminal (other than plt.subplots or plt.figure for setting up the figure/axes objects). Making a distiction between this layer and pylab is dumb. This is the layer that makes it 'like MATLAB'
the OO layer : which is what you should use in all of your scripts
Figures are the top level container objects. They can contain Axes objects and Artist objects (technically Axes are Artists, but it is useful for pedagogical reasons to distinguish between the Axes objects in a figure and the other artists (such as text objects) that are in the Figure, but not associated with an Axes) and know about the Canvas object. Each Axes can contain more Artists objects. The Artists are the useful things you want to put on your graph (lines, text, images, etc). Artists know how to draw themselves on a Canvas. When you call fig.savefig (or render the figure to the screen) the Figure object loops over all of it's children and tell them to draw them selves on to it's Canvas.
The different Backends provide implementations of the Canvas objects, hence the same figure can be rendered to a raster or vector graphic by just changing the Canvas object that is being used.
Unless you want to write a new backend, many of these details are not important and the fact that matplotlib hides them from you is why it is useful.
If the book couldn't get this correct, I would take everything it says with grain of salt.
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.