การบันทึกกราฟเป็นไฟล์ภาพจาก Jupyter/iPython Notebook ใน Matplotlib ทำได้ด้วยเมธอด plt.savefig() หรือ fig.savefig() รองรับหลายรูปแบบ: PNG, PDF, SVG, JPG
ขั้นตอนการทำงาน
- นำเข้า
matplotlib.pyplot - สร้าง Figure ด้วย
plt.figure() - เพิ่ม Axes ด้วย
fig.add_axes([left, bottom, width, height]) - พลอตข้อมูลด้วย
plt.plot() - บันทึกไฟล์ด้วย
plt.savefig('filename.png', bbox_inches='tight')
ตัวอย่างโค้ด
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
fig = plt.figure()
ax = fig.add_axes([1, 1, 1, 1])
plt.plot([1, 2])
plt.savefig('test.png', bbox_inches='tight')
พารามิเตอร์สำคัญของ savefig()
| พารามิเตอร์ | คำอธิบาย |
|---|---|
fname | ชื่อไฟล์/พาธ (副檔名กำหนด format) |
dpi | ความละเอียด (dots per inch) ค่าเริ่มต้น 100 |
bbox_inches | 'tight' ตัดขอบขาวออก ให้พอดีกับเนื้อหา |
pad_inches | ระยะห่างขอบเมื่อใช้ bbox_inches='tight' |
transparent | True ทำพื้นหลังโปร่งใส (PNG, SVG) |
facecolor | สีพื้นหลัง Figure |
edgecolor | สีขอบ Figure |
format | บังคับรูปแบบไฟล์ (png, pdf, svg, eps, jpg) |
ตัวอย่างการบันทึกหลายรูปแบบ
fig.savefig('plot.png', dpi=300, bbox_inches='tight') # 高解析度 PNG
fig.savefig('plot.pdf', bbox_inches='tight') # Vector PDF
fig.savefig('plot.svg', transparent=True, bbox_inches='tight') # SVG 透明背景
fig.savefig('plot.jpg', dpi=150, quality=95) # JPEG
ใน Jupyter Notebook
- ใช้
%matplotlib inlineแสดงใน Notebook - ใช้
plt.savefig()บันทึกไฟล์พร้อมกันได้ - หรือใช้
%%capturemagic เพื่อไม่แสดงใน Notebook แต่อยากบันทึก
การประยุกต์ใช้
เหมาะสำหรับการสร้างรายงานอัตโนมัติ การส่งออกกราฟสำหรับเอกสาร LaTeX/Word การสร้างภาพสำหรับเว็บไซต์ หรือการเก็บผลลัพธ์การทดลอง