เพื่อบันทึกรูป Matplotlib ที่เปิดอยู่ทั้งหมดในไฟล์เดียวพร้อมกัน ให้ทำตามขั้นตอน:
- กำหนดขนาดรูปและปรับระยะห่างระหว่างและรอบซับพล็อต
- สร้างรูปใหม่ (fig1) หรือเปิดใช้งานรูปที่มีอยู่ด้วย figure()
- พล็อตเส้นแรกด้วย plot()
- สร้างรูปใหม่ (fig2) หรือเปิดใช้งานรูปที่มีอยู่ด้วย figure()
- พล็อตเส้นที่สองด้วย plot()
- กำหนดตัวแปร filename สำหรับสร้างไฟล์ PDF
- สร้างฟังก์ชันผู้ใช้ save_multi_image และเรียกเพื่อบันทึกรูปทั้งหมดในไฟล์เดียว สร้างอ็อบเจกต์ PdfPages ใหม่ pp
- ดึงจำนวนรูปที่เปิดอยู่
- วนลูปรูปที่เปิดอยู่และบันทึกลงในไฟล์
- ใช้ show() เพื่อแสดงรูป
ตัวอย่าง
from matplotlib import pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
plt.rcParams["figure.figsize"] = [7.50, 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)ผลลัพธ์
การรันโค้ดจะบันทึกกราฟสองกราฟต่อไปนี้เป็นไฟล์ PDF (multi.pdf) ในไดเรกทอรีโปรเจกต์

