Matplotlib数字为PDF而不保存

时间:2015-09-16 12:08:57

标签: python pandas matplotlib reportlab

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

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

现在我不知道其他更好的选择,而不是先保存图片并稍后再使用。

我正在做类似的事情:

"./ankits/ankitt$".match(/\/([^\/]+)\//)[1]

3 个答案:

答案 0 :(得分:3)

这是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

答案 1 :(得分:1)

我认为你可以使用io.BytessIO将数字保存到缓冲区中并在platypus中使用它。这样的事可能呢?

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)

答案 2 :(得分:0)

使用我的包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)