is it possible to append figures to Matplotlib's PdfPages?

Sorry, that's a lame question. We just shouldn't use the with statement.

fig = plt.figure()
ax = fig_zoom.add_subplot(111)
ax.plot(range(10), range(10), 'b')

# create a PdfPages object
pdf = PdfPages(pdffilepath)

# save plot using savefig() method of pdf object
pdf.savefig(fig)

fig1 = plt.figure()
ax = fig_zoom.add_subplot(111)
ax.plot(range(10), range(2, 12), 'r')

pdf.savefig(fig1)

# remember to close the object to ensure writing multiple plots
pdf.close()

None of these options append if the file is already closed (e.g. the file gets created in one execution of your program and you run the program again). In that use case, they all overwrite the file.

I think appending isn't currently supported. Looking at the code of backend_pdf.py, I see:

class PdfFile(object)
...
  def __init__(self, filename):  
    ...
    fh = open(filename, 'wb')

Therefore, the function is always writing, never appending.


I think that Prashanth's answer can be generalized a bit better, for instance by incorporating it in a for loop, and avoiding the creation of multiple figures, which can generate memory leaks.

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

# create a PdfPages object
pdf = PdfPages('out.pdf')

# define here the dimension of your figure
fig = plt.figure()

for color in ['blue', 'red']:
    plt.plot(range(10), range(10), color)

    # save the current figure
    pdf.savefig(fig)

    # destroy the current figure
    # saves memory as opposed to create a new figure
    plt.clf()

# remember to close the object to ensure writing multiple plots
pdf.close()