是否可以将图形附加到Matplotlib的PdfPages中?

2024-06-08 23:30:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用PdfPages将在脚本不同部分创建的两个图形保存到PDF中,是否可以将它们附加到PDF中?

示例:

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)

Tags: addpdfplotaswithfigrangeplt
3条回答

对不起,这是个蹩脚的问题。我们不应该使用with语句。

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

我认为Prashanth's answer可以更好地进行泛化,例如将其合并到for循环中,并避免创建多个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()

如果文件已经关闭,则这些选项都不会追加(例如,文件在程序的一次执行中创建,然后再次运行程序)。在这种情况下,它们都会覆盖文件。

我认为当前不支持追加。看着backend_pdf.py的代码,我看到:

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

因此,函数总是在写,而不是附加。

相关问题 更多 >