Matplotlib图到PDF而不保存 [英] Matplotlib figure to PDF without saving

查看:96
本文介绍了Matplotlib图到PDF而不保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have to create a group of matplotlib figures, which I would like to directly present in a PDF report without saving them as a file.

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

The data for my plots is stored in a Pandas DataFrame:

现在,除了首先保存图像并在以后使用它之外,我不知道其他更好的选择.

Right now I do not know other better option than first save the image and use it later.

我正在做类似的事情:

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)

推荐答案

这是matplotlib本身提供的最佳解决方案:

Here is the best solution provided by matplotlib itself:

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) 

Voilà

在此处找到完整的示例:多页pdf matplotlib

Find a full example here: multipage pdf matplotlib

这篇关于Matplotlib图到PDF而不保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆