Matplotlib 图转 PDF 无需保存

Matplotlib figure to PDF without saving

我必须创建一组 matplotlib 图形,我想直接在 PDF 报告中显示它们而不将它们另存为文件。

我的绘图数据存储在 Pandas DataFrame 中:

现在我不知道还有什么比先保存图像然后再使用更好的选择。

我正在做类似的事情:

import matplotlib.pylab as plt
from reportlab.platypus import BaseDocTemplate, Image

for index, row in myDataFrame.iterrows():
    fig = plt.figure()
    plt.plot(row['Xvalues'], row['Yvalues'],'o', color='r')
    fig.savefig('figure_%s.png' % (row['ID']))
    plt.close(fig)

text = []
doc = BaseDocTemplate(pageName, pagesize=landscape(A4))

for f in listdir(myFolder):
    if f.endswith('png'):
        image1 = Image(f)
        text.append(image1)

doc.build(text)

我认为您可以使用 io.BytessIO 将图形保存到缓冲区中并在鸭嘴兽中使用它。也许是这样的?

import io
import matplotlib.pylab as plt
from reportlab.platypus import BaseDocTemplate, Image

buffers = []

for index, row in myDataFrame.iterrows():
    fig = plt.figure()
    plt.plot(row['Xvalues'], row['Yvalues'],'o', color='r')

    mybuffer = io.BytesIO()
    fig.savefig(mybuffer, format = 'pdf')
    mybuffer.seek(0)
    buffers.append(mybuffer)
    plt.close(fig)

text = []
doc = BaseDocTemplate(pageName, pagesize=landscape(A4))

doc.build(buffers)

下面是matplotlib自己提供的最佳方案:

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

with PdfPages('foo.pdf') as pdf:
    #As many times as you like, create a figure fig and save it:
    fig = plt.figure()
    pdf.savefig(fig)

    ....
    fig = plt.figure()
    pdf.savefig(fig) 

在此处查找完整示例:multipage pdf matplotlib

使用我的包 autobasedoc https://pypi.org/project/autobasedoc/ 你的例子看起来像这样:

from autobasedoc import autorpt as ar
from autobasedoc import autoplot as ap

@ap.autoPdfImg
def my_plot(index, row, canvaswidth=5): #[inch]
    fig, ax = ap.plt.subplots(figsize=(canvaswidth,canvaswidth))
    fig.suptitle(f"My simple plot {index}", fontproperties=fontprop)
    ax.plot(row['Xvalues'], row['Yvalues'],label=f"legendlabel{index}")
    return fig

doc = ar.AutoDocTemplate(pageName)

content = []

for index, row in myDataFrame.iterrows():
    content.append(my_plot(index, row))

doc.build(content)