matplotlib figure vs subplot vs axes? - python

Though I've been able to create basic plots with matplotlib.pyplot before, I cannot fully understand what the difference between these are:
figure
subplot
axes
(axis?)
As I understand, all three of these are objects for the area in which a graph is drawn, so what distinguishes them in terms of what can be drawn inside them?

Matplotlib's user guide gives a great description about the parts of a figure.

The components are hierarchical:
Figure object: the whole figure
Axes object: belongs to a Figure object and is the space where we add the data to visualize
Axis object: belongs to an Axes object. Axis object can be categorized as XAxis or YAxis.
For further info, visit this link:
Getting Started with Matplotlib

Related

Python3 - Plotting the same matplotlib axes object on multiple figures?

I have a script which I'm adapting to include a GUI. In it, I create a plot with subplots (the arrangement of which depends on the number of plots - e.g. 4 plots go into a square rather than 4-across). That plot (with a subplot for each of the "targets" analyzed) gets saved to a .png.
In building the GUI, I'm writing up the 'results' frame and would like to show these individual subplots on their own tabs. I've written the code to lay out the frame how I want it, but in order to separate the subplots into their own plots, I need to draw the completed Axes object (e.g. the entire subplot for that target) onto a new figure in the frame.
Since the number of subplots isn't known before runtime, I already have my Axes objects/subplots in an array (/list?) axs, whose members are the individual Axes objects (each containing data points created with ax.scatter() and several lines and annotations created with ax.plot() and ax.annotate).
When I initially create the axes, I do so with
fig, axs = plt.subplots(num='Title', nrows=numrow, ncols=numcol,
figsize=[numcol*5, numrow*5],
subplot_kw={'adjustable':'box', 'aspect':1})
Is there a way to now take these axes and draw them onto a new figure (the one that will be contained in the 'results' frame of the GUI)? In my searches, I only came up with ways to plot multiple axes onto a single figure (i.e. how to use subplots()) but nothing came up on how I'd throw a pre-existing Axes object into a new figure that it wasn't originally associated with. I'd rather not re-draw the axes from scratch -- there's quite a bit of decoration and multiple datasets / lines plotted onto them already.
Any ideas? Happy to post code as requested, but since this more of a "How do I do this" than a "why doesn't my code work", I didn't post much of it.
Thank you!
I believe that's not possible and you will have to recreate the Axes objects inside the other figure. Which is just a matter of code reorganization. Note that your approach would not noticeably improve rendering performance. Matplotlib would have to re-render the Axes objects anyway, and that's the computationally expensive part. Creating the objects is relatively cheap.
What you're trying to do is pretty much this:
from matplotlib import pyplot
pyplot.ion()
figure1 = pyplot.figure()
axes = figure1.add_subplot()
axes.plot([0, 1], [0, 1])
figure2 = pyplot.figure()
figure2.add_axes(axes)
Which raises:
ValueError: The Axes must have been created in the present figure
And the documentation of add_axes() notes:
In rare circumstances, add_axes may be called with a single argument, an Axes instance already created in the present figure but not in the figure's list of Axes.
So that's a pretty clear indication that this is not a supported use case.

How to add a clear border around a graph with matplotlib.pyplot

I created a stacked barchart using matplotlib.pyplot but there is no border around the graph so the title of the graph and axes are right up against the edge of the image and get cutoff in some contexts when I use it. I would like to add a small clear or white border around the graph, axes and title. repos_amount is a pandas DataFrame.
Here is my code:
colors = ["Green", "Red","Blue"]
repos_amount[['Agency','MBS','Treasury']].plot.bar(stacked=True, color=colors, figsize=(15,7))
plt.title('Total Outstanding Fed Repos Operations', fontsize=16)
plt.ylabel('$ Billions', fontsize=12)
Here is what the graph looks like:
I tried the suggestions from the link below and I could not figure out how to make it work. I'm not good with matplotlib yet so I would need help figuring out how to apply it to my code.
How to draw a frame on a matplotlib figure
Try adding plt.tight_layout() to the bottom of your code.
Documentation indicates that this tries to fit the titles, labels etc within the subplot figure size, rather than adding items around this figure size.
It can have undesirable results if your labels or headings are too big, in which case you would then need to look into the answers in this thread to adjust the specific box size of your chart elements.

What exactly is a matplotlib axes object?

When we create a new figure:
import matplotlib.pyplot as plt
fig = plt.figure()
we can see in the console an output like:
<Figure size 432x288 with 0 Axes>
so when we use add_axes:
add_axes(rect, projection=None, polar=False, **kwargs)
are we actually defining the x,y axes that encompass the "box" that will bound the figure (the axes in a more mathematical sense) and nothing more? or in fact this line of code is creating an empty figure with the desired dimensions in which any data we add later will be fitted in? (or None of the above maybe?)
That questioning left me wondering how can I physically understand what the axes are for matplotlib.
Thanks for helping.
From the point of view of the viewer, the axes is the box which will contain the data and which (usually) has an x-axis and y-axis.
From the programmatical point of view, the axes is an object, which stores several other objects like XAxis, YAxis and provides methods to create plots. Importantly, it has a transformation stored, which allows to draw the data points in pixel space.

Data visualization in python (matplotlib) [duplicate]

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.

What is the difference between axes and pyplot

I am trying to embed matplotlib figure into PyQt4, but when I try to plot the figure using pyplot, it's giving an error or would make a separate matplotlib built-in figure object rather than plotting into my canvas.
If I try to plot using axes, all is good as figure gets plotted into the canvas. However, I can't plot two axes into a single graph which was done by pyplot by simply plotting two plots one after another.
So how can I 2 plots into one graph using axes?
class Foo(blah):
""" some code here """
# code which giving error:
self.pyplot.plot_date(x,y)
self.pyplot.plot_date(a,b)
# code plotting matplotlib figure object rather drawing into canvas
pyplot.plot_date(x,y)
pyplot.plot_date(a,b)
# code only plotting only a,b - but not x,y
self.axes.plot_date(x,y)
self.axes.plot_date(a,b)

Categories

Resources