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

วิธีทำให้ฟอนต์ Matplotlib ตรงกับ LaTeX Output


ภาพรวม

สาธิตการใช้ Font Properties เพื่อให้ฟอนต์ใน Matplotlib ใกล้เคียงกับ LaTeX Output โดยใช้ฟอนต์ภายนอก

ขั้นตอน

  1. โหลด Font Properties จากไฟล์ TTF
  2. สร้างข้อมูล X, Y (y = sin(x))
  3. พลอตด้วย Label ใช้ LaTeX Syntax r'$\sin (x)$'
  4. ตั้งค่า Title ด้วย Font Properties ที่โหลดมา
  5. แสดงผล

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

import numpy as np
from matplotlib import pyplot as plt, font_manager as fm

fprop = fm.FontProperties(fname='/usr/share/fonts/truetype/malayalam/Karumbi.ttf')

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

x = np.linspace(1, 10, 1000)
y = np.sin(x)
plt.plot(x, y, label=r'$\sin (x)$', c="red", lw=2)
plt.title(label=r'$\sin (x)$', fontproperties=fprop)
plt.show()

ผลลัพธ์

กราฟ Sine Wave พร้อม Title และ Legend ใช้ฟอนต์ Karumbi (Malayalam) แทนฟอนต์ Default

วิธีมาตรฐานสำหรับ LaTeX Look

plt.rcParams.update({
    "text.usetex": True,
    "font.family": "serif",
    "font.serif": ["Computer Modern Roman"]
})

ต้องมี LaTeX ติดตั้งในระบบ