There is an extremely useful feature in R that allows you to generate multi-page PDF files for a series of plots. Say you have a bunch of neurons and want to plot something useful for each cell. The pdf() device will generate a new page each time you generate a plot:
pdf("output.pdf",...)
for (cell in cells)
plot.data(cell)
dev.off()
For a similar effect in matplotlib you can use the following python class, which uses LaTeX to generate a fairly simple layout of one or more plots on a page. The code is adapted from an implementation in MATLAB by Zhiyi Chi. You will need to have some implementation of LaTeX on your system. By default, the class generates EPS files for each figure, which means LaTeX needs to generate a DVI file that is subsequently transformed into a PDF by dvipdf. Obviously this could be implemented using pdflatex with figures exported as PNG or PDF files, which is left as an exercise to the reader. Figure files are maintained in a temporary directory, which will be cleaned up when the object is garbage-collected, but if python crashes your files probably won't be deleted.
import os, tempfile, shutil, matplotlib
class texplotter(object):
"""
This class is used to group a bunch of figures into a single pdf
file. On initialization it creates a temporary directory where eps
files and the tex input file are stored. Each call to
plotfigure() generates a new eps file. Entries are stored in the
figures attribute for each subplot/file. Calling makepdf() causes
the tex file to be compiled, and a pdf file is saved in the
location specified. Destruction of the object results in cleanup
of the temporary directory.
"""
_defparams = params = {'backend': 'ps',
'axes.labelsize': 10,
'text.fontsize': 10,
'xtick.labelsize': 8,
'ytick.labelsize': 8,
'text.usetex': False}
_latex_cmd = "latex %s > /dev/null"
_pdf_cmd = "dvipdf -dAutoRotatePages=/None %s"
def __init__(self, parameters=None, leavetempdir=False):
"""
Initialize the texplotter object. This creates the temporary
directory and the texfile.
Optional arguments:
margins - set the margins of the output file (inches, inches)
plotdims - set the default dimensions of plots (inches, inches)
parameters - a dictionary which is used to set values in matplotlib.rcParams.
For instance, tx = texplotter(parameters={'font.size':8.0})
The default margins and plotdims will plot 8 figures per page.
"""
if parameters!=None:
self._defparams.update(parameters)
matplotlib.rcParams.update(self._defparams)
self._tdir = tempfile.mkdtemp()
self._leavetempdir = leavetempdir
self.figures = []
def __del__(self):
if hasattr(self, '_tdir') and os.path.isdir(self._tdir) and not self._leavetempdir:
shutil.rmtree(self._tdir)
def plotfigure(self, fig, plotdims=None, closefig=True):
"""
Calls savefig() on the figure object to save an eps file. Adds the figure
to the list of plots.
- override figure dimensions
- by default, closes figure after it's done exporting the EPS file;
set to True to keep the figure
"""
if plotdims==None:
plotdims = fig.get_size_inches()
figname = "texplotter_%03d.eps" % len(self.figures)
fig.savefig(os.path.join(self._tdir, figname))
self.figures.append([figname, plotdims])
if closefig:
from pylab import close
close(fig)
def pagebreak(self):
""" Insert a pagebreak in the file """
self.figures.append(None)
def writepdf(self, filename, margins=(0.5, 0.9)):
"""
Generates a pdf file from the current figure set.
filename - the file to save the pdf to
"""
fp = open(os.path.join(self._tdir, 'texplotter.tex'), 'wt')
fp.writelines(['\\\\documentclass[10pt,letterpaper]{article}\
',
'\\\\usepackage{graphics, epsfig}\
',
'\\\\usepackage[top=%fin,bottom=%fin,left=%fin,right=%fin,nohead,nofoot]{geometry}' % \\
(margins[1], margins[1], margins[0], margins[0]),
'\\\\setlength{\\\\parindent}{0in}\
',
'\\\\begin{document}\
',
'\\\\begin{center}\
'])
for fig in self.figures:
if fig==None:
fp.write('\\\\clearpage\
')
else:
figname, plotdims = fig
fp.write('\\\\includegraphics[width=%fin,height=%fin]{%s}\
' % (plotdims + (figname,)))
fp.write('\\\\end{center}\
\\\\end{document}\
')
fp.close()
pwd = os.getcwd()
if not os.path.isabs(filename): filename = os.path.join(pwd, filename)
try:
os.chdir(self._tdir)
os.system(self._latex_cmd % 'texplotter.tex')
if not os.path.exists('texplotter.dvi'): raise IOError, "Latex command failed"
os.system(self._pdf_cmd % 'texplotter.dvi')
if not os.path.exists('texplotter.pdf'): raise IOError, "dvipdf command failed"
shutil.move('texplotter.pdf', filename)
finally:
os.chdir(pwd)