[英]Saving multiple plots to one pdf file
我正在嘗試將多個圖保存在一個 pdf 文件中。
任何人都可以幫助以下代碼嗎?
這段代碼有什么問題:
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
import random as rand
pdfFile = PdfPages("output.pdf")
for i in range(10):
xVals = [x for x in range(20)]
yVals = [rand.randint(50,100) for x in xVals]
plt.figure(figsize=(20,10))
fig = plt.plot(xVals , yVals)
plt.xlabel('Data point')
plt.ylabel('Strain [us]')
plt.title(i)
#plt.show()
pdfFile.savefig(fig)
print(i)
pdfFile.close()
plot
作為Line2D
的列表返回(在您的情況下只有一個)。 從這一行中,您需要使用get_figure
獲取圖形:
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
import random as rand
pdfFile = PdfPages("output.pdf")
for i in range(10):
xVals = [x for x in range(20)]
yVals = [rand.randint(50,100) for x in xVals]
plt.figure(figsize=(20,10))
line, = plt.plot(xVals , yVals)
plt.xlabel('Data point')
plt.ylabel('Strain [us]')
plt.title(i)
#plt.show()
pdfFile.savefig(line.get_figure())
print(i)
pdfFile.close()
如果savefig
中沒有指定圖形,則保存當前圖形,因此您也可以簡單地編寫:
plt.plot(xVals , yVals)
pdfFile.savefig()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.