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

16.5k views Asked by At

I want to save 2 figures created at different parts of a script into a PDF using PdfPages, is it possible to append them to the pdf?

Example:

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

with PdfPages(pdffilepath) as pdf:
    pdf.savefig(fig)

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

with PdfPages(pdffilepath) as pdf:
    pdf.savefig(fig1)
5

There are 5 answers

1
Prashanth On BEST ANSWER

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()
0
Jose On
import matplotlib.pyplot as plt 
from matplotlib.backends.backend_pdf import PdfPages

# Use plt to draw whatever you want  
pp = PdfPages('multipage.pdf')
plt.savefig(pp, format='pdf')
pp.savefig()

# Finally, after inserting all the pages, the multipage pdf object has to be closed.  
pp.close()
0
mgalardini On

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()
0
surya On

You can directly do like this if your data is in data frame

#
with PdfPages(r"C:\Users\ddadi\Documents\multipage_pdf1.pdf","a") as pdf:
    #insert first image
    dataframe1.plot(kind='barh'); plt.axhline(0, color='k')
    plt.title("first page")
    pdf.savefig()
    plt.close()

    #insert second image
    dataframe2.plot(kind='barh'); plt.axhline(0, color='k')
    plt.title("second page")
    pdf.savefig()
    plt.close()
0
user3450049 On

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.