Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การส่งออกไฟล์ SVG จาก figure ใน Matplotlib


บันทึก figure เป็นไฟล์ SVG

ใช้เมธอด savefig() บันทึกเป็นไฟล์ .svg

ขั้นตอน

  1. ตั้งค่าขนาด figure และปรับ padding
  2. สร้าง figure และ subplots
  3. สร้างข้อมูล x, y สุ่มด้วย NumPy
  4. วาดกราฟด้วย plot()
  5. บันทึกไฟล์ .svg ด้วย savefig()

ตัวอย่างโค้ด

import numpy as np
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

fig, ax = plt.subplots()
x = np.random.rand(10)
y = np.random.rand(10)
ax.plot(x, y, ls='dotted', linewidth=2, color='red')
plt.savefig("myimg.svg")

ผลลัพธ์

เมื่อรันโค้ด จะสร้างไฟล์ SVG ชื่อ "myimg.svg" บันทึกไว้ในโฟลเดอร์ปัจจุบัน

การส่งออกไฟล์ SVG จาก figure ใน Matplotlib