11
votes

I have a lengthy plot, composed o several horizontal subplots organized into a column.

When I call fig.savefig('what.pdf'), the resulting output file shows all the plots crammed onto a single page.

Question: is there a way to tell savefig to save on any number (possibly automatically determined) of pdf pages?

I'd rather avoid multiple files and then os.system('merge ...'), if possible.

3

3 Answers

10
votes

I haven't tried myself, but in the matplolib faq there are some instruction to save plots in pdf in several pages.

1
votes

I suspect that there is a more elegant way to do this, but one option is to use tempfiles or StringIO to avoid making traditional files on the system and then you can piece those together.

0
votes

I was wondering how to perform a similar thing. I have a set plots coming from different image files, which vary depending on the file. So the idea is, once I found a nice number of plots that can be plotted in a page, apply this for the files. Luckly, I found a solution suggested here: http://blog.marmakoide.org/?p=94. However it does not work correctly, since it only plots the first panel plots, leaving the rest of the panels empty. I modified it and here I include a working version for a (1XN) grid and the output plots.

import numpy

from matplotlib import pyplot as plot
from matplotlib.backends.backend_pdf import PdfPages

# Generate the data
data = numpy.random.randn(7, 1024)

# The PDF document
pdf_pages = PdfPages('histograms.pdf')

# Generate the pages
nb_plots = data.shape[0]
nb_plots_per_page = 5
nb_pages = int(numpy.ceil(nb_plots / float(nb_plots_per_page)))
grid_size = (nb_plots_per_page, 1)

for i, samples in enumerate(data):
  print
  print i,i % nb_plots_per_page,samples
  # Create a figure instance (ie. a new page) if needed
  if i % nb_plots_per_page == 0:
    print 'Opening'
    fig = plot.figure(figsize=(8.27, 11.69), dpi=100)
  # Close the page if needed
  elif (i + 1) % nb_plots_per_page == 0 or (i + 1) == nb_plots:
    plot.subplot2grid(grid_size, (i % nb_plots_per_page, 0))
    plot.hist(samples, 32, normed=1, facecolor='#808080', alpha=0.75)
    plot.title(str(i+1))

    plot.tight_layout()
    pdf_pages.savefig(fig)
    print 'Closing'
    print i,samples
    # Plot stuffs !
  print i,samples
  plot.subplot2grid(grid_size, (i % nb_plots_per_page, 0))
  plot.hist(samples, 32, normed=1, facecolor='#808080', alpha=0.75)
  plot.title(str(i+1))


# Write the PDF document to the disk
pdf_pages.close()
print 'histograms.pdf'

Page1

Page2