Matplotlib - 多頁 PDF



一個多頁PDF(行動式文件格式)是一種檔案型別,可以將多個頁面或影像儲存在一個文件中。PDF中的每個頁面都可以具有不同的內容,例如圖表、影像或文字。

Matplotlib 透過其backend_pdf.PdfPages模組提供建立多頁PDF的支援。此功能允許使用者在同一個PDF檔案中跨多個頁面儲存繪圖和視覺化結果。

在某些情況下,需要將多個繪圖儲存到一個檔案中。雖然許多影像檔案格式(如PNG、SVG或JPEG)通常只支援每個檔案一個影像,但Matplotlib提供了一種建立多頁輸出的解決方案。PDF就是這樣一種支援的格式,它允許使用者有效地組織和共享視覺化結果。

建立基本的 多頁 PDF

要使用Matplotlib在PDF文件中儲存多個頁面的繪圖,可以使用PdfPages類。此類簡化了生成包含多個頁面的PDF檔案的過程,每個頁面包含不同的視覺化結果。

示例

讓我們從一個基本的示例開始,演示如何使用Matplotlib建立多頁PDF。此示例將多個圖形一次性儲存到一個PDF檔案中。

from matplotlib.backends.backend_pdf import PdfPages
import numpy as np
import matplotlib.pyplot as plt

# sample data for plots
x1 = np.arange(10)
y1 = x1**2

x2 = np.arange(20)
y2 = x2**2

# Create a PdfPages object to save the pages
pp = PdfPages('Basic_multipage_pdf.pdf')

def function_plot(X,Y):
   plt.figure()
   plt.clf()

   plt.plot(X,Y)
   plt.title('y vs x')
   plt.xlabel('x axis', fontsize = 13)
   plt.ylabel('y axis', fontsize = 13)
   pp.savefig()

# Create and save the first plot
function_plot(x1,y1)
# Create and save the second plot
function_plot(x2,y2)

pp.close()

輸出

執行上述程式後,將在儲存指令碼的目錄中生成'Basic_multipage_pdf.pdf'。

multipage_pdf_ex1

新增元資料和註釋

Matplotlib還支援向多頁PDF新增元資料和註釋。元資料可以包括標題、作者和建立日期等資訊,為PDF中的內容提供額外的上下文或詳細資訊。

示例

這是一個高階示例,它建立一個包含元資料和註釋的多頁PDF。

import datetime
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages

# Create the PdfPages object to save the pages
with PdfPages('Advanced_multipage_pdf.pdf') as pdf:

   # Page One
   plt.figure(figsize=(3, 3))
   plt.plot(range(7), [3, 1, 4, 1, 5, 9, 2], 'r-o')
   plt.title('Page One')
   # saves the current figure into a pdf page
   pdf.savefig()  
   plt.close()

   # Page Two

   # Initially set it to True. If LaTeX is not installed or an error is caught, change to `False`
   # The usetex setting is particularly useful when you need LaTeX features that aren't present in matplotlib's built-in mathtext.
   plt.rcParams['text.usetex'] = False
   plt.figure(figsize=(8, 6))
   x = np.arange(0, 5, 0.1)
   plt.plot(x, np.sin(x), 'b-')
   plt.title('Page Two')
   # attach metadata (as pdf note) to page
   pdf.attach_note("plot of sin(x)")  
   pdf.savefig()
   plt.close()

   # Page Three
   plt.rcParams['text.usetex'] = False
   fig = plt.figure(figsize=(4, 5))
   plt.plot(x, x ** 2, 'ko')
   plt.title('Page Three')
   pdf.savefig(fig)  
   plt.close()

   # Set file metadata
   d = pdf.infodict()
   d['Title'] = 'Multipage PDF Example'
   d['Author'] = 'Tutorialspoint'
   d['Subject'] = 'How to create a multipage pdf file and set its metadata'
   d['Keywords'] = 'PdfPages multipage keywords author title subject'
   d['CreationDate'] = datetime.datetime(2024, 1, 15)
   d['ModDate'] = datetime.datetime.today()

輸出

執行上述程式後,將在儲存指令碼的目錄中生成'Advanced_multipage_pdf.pdf'。您將能夠觀察到如下詳細資訊:

multipage_pdf_ex2
廣告