Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách có được font giống LaTeX trong đầu ra Matplotlib

Để font đầu ra Matplotlib khớp với LaTeX, sử dụng FontProperties với file font TTF.

  • Tạo dữ liệu x, y = sin(x).
  • Vẽ đồ thị với label LaTeX r'$\sin (x)$'.
  • Đặt title với fontproperties từ file font hệ thống.
  • Hiển thị bằng show().

Ví dụ

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()

Kết quả

Đồ thị sin(x) với tiêu đề sử dụng font TTF tùy chỉnh, label LaTeX.