To create subplots in matplotlib, you can use the subplot() command, as a standalone function or a method on the figure class. The following commands create or access the first subplot in a column of two:
subplot(211)
fig.add_subplot(211)
The main difference is that the method will not overwrite existing axes in the figure, and you have to call draw() to update the figure. In general I prefer to use the object-oriented interface whenever possible as this minimizes the number of imports I have to do, which is probably just an aesthetic thing.
One feature in MATLAB that I occasionally miss is the ability to create more sophisticated layouts can be used by specifying a finely-grained grid and then accessing multiple cells. For instance, to create axes that use 3/5s of the vertical space:
subplot(5,1,[1,2,3]).
Eventually I missed it enough that I wrote this function, which allows you to create a row of plots with a given vertical position and height. The plots can be the same size, and evenly spaced, or you can use the plotw argument to adjust the width of particular plots. I also have a similar function I use for producing the same effect vertically. Writing some kind of omnibus gridding function is left as an exercise for the reader.
import numpy as nx
def xplotlayout(fig, nplots, xstart=0.05, xstop=1.0, spacing=0.01,
bottom=0.1, top = 0.9, plotw=None, **kwargs):
"""
Generates a series of plots neighboring each other horizontally and with common
y offset and height values.
fig - the figure in which to create the plots
nplots - the number of plots to create
xstart - the left margin of the first plot
xstop - the right margin of the last plot
spacing - the amount of space between plots
bottom - the bottom margin of the row of plots
top - the top margin of the row of plots
plotw - specify the width of each plot. By default plots are evenly spaced, but
if a list of factors is supplied the plots will be adjusted in width. Note
that if the total adds up to more than the plots will exceed the
boundaries specified by xstart and xstop
kwargs - passed to axes command
"""
ax = []
xwidth = (xstop - xstart - spacing * (nplots-1))/ nplots
xpos = xstart
yheight = top - bottom
if plotw==None: plotw = nx.ones(nplots)
for j in range(nplots):
xw = xwidth * plotw[j]
rect = [xpos, bottom, xw, yheight]
a = fig.add_axes(rect, **kwargs)
xpos += xw + spacing
ax.append(a)
return ax
amcleod wrote: