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:
Related
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.
import matplotlib.pyplot as plt
plt.plot([1,2,3],[1,2,3],'ro')
plt.axis([-4,4,-4,4])
plt.savefig('azul.png')
plt.plot([0,1,2],[0,0,0],'ro')
plt.axis([-4,4,-4,4])
plt.savefig('amarillo.png')
Output:
Why does this happen and how to solve?
What you see is a completely expected behaviour. You can plot as many data as often as you want to the same figure, which is very often very useful.
If you want to create several figures in the same script using the matplotlib state machine, you need to first close one figure before generating the next.
So in this very simple case, just add plt.close() between figure creation.
import matplotlib.pyplot as plt
plt.plot([1,2,3],[1,2,3],'bo')
plt.axis([-4,4,-4,4])
plt.savefig('azul.png')
plt.close()
plt.plot([0,1,2],[0,0,0],'yo')
plt.axis([-4,4,-4,4])
plt.savefig('amarillo.png')
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())?
programming noob here. I'm trying to use a matplotlib widget in a PyQt4 GUI. The widget is similar to matplotlib's example for qt.
At some point the user needs to click on the plot, which I thought something like ginput() would handle. However, this doesn't work because the figure doesn't have a manager (see below). Note that this is very similar to another question but it never got answered.
AttributeError: 'NoneType' object has no attribute 'manager'
Figure.show works only for figures managed by pyplot, normally created by pyplot.figure().
I'm assuming by "normally" there's a way around this.
Another simple script to demonstrate:
from __future__ import print_function
from matplotlib.figure import Figure
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 5, 0.1)
y = np.sin(x)
# figure creation by plt (also given a manager, although not explicitly)
plt.figure()
plt.plot(x,y)
coords = plt.ginput() # click on the axes somewhere; this works
print(coords)
# figure creation w/o plt
manualfig = Figure()
manualaxes = manualfig.add_subplot(111)
manualaxes.plot(x,y)
manualfig.show() # will fail because of no manager, yet shown as a method
manualcoords = manualfig.ginput() # comment out above and this fails too
print(manualcoords)
As popular as pyplot is (I can't hardly find an answer without it), it doesn't seem to play nice when working with a GUI. I thought pyplot was simply a wrapper for the OO framework but I guess I'm just a noob.
My question then is this:
Is there some way to attach pyplot to an instance of matplotlib.figure.Figure?
Is there an easy way to attach a manager to a Figure? I found new_figure_manager() in matplotlib.backends.backend_qt4agg, but couldn't get it to work, even if it is the right solution.
Many thanks,
James
pyplot is just a wrapper for the OO interface, but it does a lot of work for you read the example you link to again carefully, the
FigureCanvas.__init__(self, fig)
line is very important as that is what tells the figure what canvas to use. The Figure object is just a collection of Axes objects (and a few Text objects), the canvas object is what knows how to turn Artist objects (ie matplotlib's internal representation of lines, text, points, etc) in to pretty colors. Also see something I wrote for another embedding example which does not sub-class FigureCanvas.
There is a PR to make this process easier, but it is stalled while we get 1.4 out the door.
also see: Which is the recommended way to plot: matplotlib or pylab?, How can I attach a pyplot function to a figure instance?
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.