ในการแปลง matplotlib figure เป็น PIL image object เราสามารถทำตามขั้นตอนต่อไปนี้:
- ตั้งค่าขนาดรูปและปรับ padding ระหว่างและรอบ subplots
- สร้าง figure ใหม่หรือเปิดใช้งาน figure ที่มีอยู่
- พลอटलิสต์ด้วยเมธอด plot()
- เริ่มต้น in-memory buffer
- บันทึกภาพใน buffer
- ใช้ PIL image เพื่อรับอ็อบเจ็กต์ภาพ
- แสดงภาพปัจจุบัน
- ปิด in-memory I/O buffer
ตัวอย่าง
import io from PIL import Image import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True plt.figure() plt.plot([1, 2]) img_buf = io.BytesIO() plt.savefig(img_buf, format='png') im = Image.open(img_buf) im.show(title="My Image") img_buf.close()
ผลลัพธ์

