是否有可能将数字附加到Matplotlib的PdfPages?

Pra*_*nth 6 python matplotlib pdfpages

我想使用PdfPages将在脚本的不同部分创建的2个数字保存为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)
Run Code Online (Sandbox Code Playgroud)

Pra*_*nth 6

对不起,这是一个蹩脚的问题.我们不应该使用该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()
Run Code Online (Sandbox Code Playgroud)


mga*_*ini 6

我认为Prashanth 的答案可以更好地概括,例如将其合并到 for 循环中,并避免创建多个数字,这可能会产生内存泄漏

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()
Run Code Online (Sandbox Code Playgroud)


use*_*049 5

如果文件已经关闭,则这些选项都不会附加(例如,文件是在程序的一次执行中创建的,然后您再次运行程序)。在那个用例中,它们都覆盖了文件。

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

class PdfFile(object)
...
  def __init__(self, filename):  
    ...
    fh = open(filename, 'wb')
Run Code Online (Sandbox Code Playgroud)

因此,该函数始终在写入,从不追加。