將多個figure儲存到一個matplotlib PDF檔案中
要同時將多張圖片儲存到一個PDF檔案中,我們可以按下列步驟進行
步驟
設定figure大小並調整子圖之間的邊距
建立一個新的figure (fig1)或使用 figure() 方法啟用現有的figure
使用plot() 方法繪製第一條線
建立一個新的figure (fig2)或使用 figure() 方法啟用現有的figure
使用plot() 方法繪製第二條線
初始化一個變數filename來製作一個PDF檔案
建立使用者自定義函式 save_multi_image() 將多張圖片儲存到一個PDF檔案中
使用filename呼叫函式save_multi_image()
建立一個新的PdfPages物件
獲得開啟figure的數量
迭代開啟的figure,將它們儲存到檔案中
關閉建立的PDF物件
示例
from matplotlib import pyplot as plt from matplotlib.backends.backend_pdf import PdfPages plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True fig1 = plt.figure() plt.plot([2, 1, 7, 1, 2], color='red', lw=5) fig2 = plt.figure() plt.plot([3, 5, 1, 5, 3], color='green', lw=5) def save_multi_image(filename): pp = PdfPages(filename) fig_nums = plt.get_fignums() figs = [plt.figure(n) for n in fig_nums] for fig in figs: fig.savefig(pp, format='pdf') pp.close() filename = "multi.pdf" save_multi_image(filename)
輸出

執行後,它將在專案目錄中建立一個名為“multi.pdf”的PDF檔案,並將以下兩張圖片儲存到該檔案中

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP