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

วิธีโหลดไฟล์ .ttf ใน Matplotlib ด้วย mpl.rcParams

การใช้ฟอนต์ TTF กำหนดเองใน Matplotlib

สามารถโหลดไฟล์ฟอนต์ .ttf และตั้งเป็นฟอนต์เริ่มต้นได้ผ่าน font_manager และ rcParams

ขั้นตอนหลัก

  • ตั้งค่าขนาดรูปและ padding
  • ระบุเส้นทางไฟล์ .ttf
  • สร้าง FontProperties จากไฟล์ฟอนต์
  • ตั้งค่า font family ด้วยชื่อฟอนต์จาก FontProperties
  • สร้าง figure และ subplots
  • ตั้งค่า title เพื่อทดสอบฟอนต์
  • แสดงผลด้วย show()

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

from matplotlib import pyplot as plt, font_manager as fm

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

path = '/usr/share/fonts/truetype/malayalam/Karumbi.ttf'
fprop = fm.FontProperties(fname=path)
plt.rcParams['font.family'] = fprop.get_name()

fig, ax = plt.subplots()
ax.set_title('This is my title!', size=40)
plt.show()

หมายเหตุ

เส้นทางไฟล์ฟอนต์ต้องถูกต้องและเข้าถึงได้ในระบบปฏิบัติการ