简体   繁体   English

使用 PyFPDF 将 Matplotlib 子图保存为 PDF

[英]Save Matplotlib subplot as PDF using PyFPDF

I am trying to create two figures with two plots in each figure and then create a PDF file with one of the figures.我正在尝试创建两个图,每个图中有两个图,然后使用其中一个图创建一个 PDF 文件。 I want to choose which figure will be saved in the PDF file.我想选择将哪个图形保存在 PDF 文件中。 I have this simple code.我有这个简单的代码。 It's just an example:这只是一个例子:

from fpdf import FPDF
from matplotlib import pyplot as plt
import tempfile
import io

# Examples
X = [0, 1, 2, 3, 4, 5, 6]
Y = [0, 1, 0, 1, 0, 1, 0]

X1 = [0, 1, 2, 3, 4, 6, 7, 8, 9, 10]
Y1 = [1, 4, 6, 4, 2, 12, 4, 6, 3, 12]

X2 = [0, 1, 2, 3, 4, 6, 7, 8, 9, 10]
Y2 = [1, 1, 1, 3, 6, 12, 18, 24, 30, 36]

X3 = [0, 1, 2, 3, 4, 6, 7, 8, 9, 10]
Y3 = [1, 30, 20, 30, 10, 30, 40, 40, 50, 20]


def plot(x,y, x1, y1):

    fig, (ax1, ax2) = plt.subplots(1, 2)
    ax1.plot(x, y)
    ax2.plot(x1, y1)

    return fig

def pdf_generator():

    fig = io.BytesIO()
    plt.savefig(fig, format="png")
    saved_fig = tempfile.NamedTemporaryFile()

    with open(f"{saved_fig.name}.png", 'wb') as sf:
        sf.write(fig.getvalue())

    pdf = FPDF('P', 'mm', 'A4')
    pdf.add_page(orientation='P', format='A4')
    pdf.set_xy(30, 50)
    pdf.image(fig, w=140, h=110)
    fig.close()

    return pdf.output('pdf_plot.pdf')

figA = plot(X1,Y1, X2,Y2)
figB = plot(X,Y, X3,Y3)

pdf_generator()

I created the figA and the figB .我创建了figAfigB However, the figure that is always "converted" to PDF is the figB .但是,始终“转换”为 PDF 的图形是figB I already tried to create a pdf_generator function that would accept as a parameter the figure's name but it didn't work.我已经尝试创建一个 pdf_generator 函数,该函数将接受图形名称作为参数,但它不起作用。

Any suggestion to solve this problem?有什么建议可以解决这个问题吗?

You're nearly there, you just need to change your function definition to take as an argument the figure you want to plot, and save it using figure.savefig() rather than plt.savefig :您快到了,您只需要更改函数定义以将要绘制的图形作为参数,并使用figure.savefig()而不是plt.savefig保存它:

#...
def pdf_generator(figure):
    fig = io.BytesIO()
    figure.savefig(fig, format="png")
    #...

pdf_generator(figA)
pdf_generator(figB)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM