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

五迷三道 提交于 2019-11-29 10:49:37

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()

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()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!