我正在嘗試創建兩個圖,每個圖中有兩個圖,然后使用其中一個圖創建一個 PDF 檔案。我想選擇將哪個圖形保存在 PDF 檔案中。我有這個簡單的代碼。這只是一個例子:
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()
我創建了figA和figB。但是,始終“轉換”為 PDF 的數字是figB. 我已經嘗試創建一個 pdf_generator 函式,該函式將接受圖形名稱作為引數,但它不起作用。
有什么建議可以解決這個問題嗎?
uj5u.com熱心網友回復:
您快到了,您只需要更改函式定義以將要繪制的圖形作為引數,并使用figure.savefig()而不是保存它plt.savefig:
#...
def pdf_generator(figure):
fig = io.BytesIO()
figure.savefig(fig, format="png")
#...
pdf_generator(figA)
pdf_generator(figB)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/478895.html
