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

Cách nhúng font vào PDF do Matplotlib tạo?

Để nhúng font vào PDF do Matplotlib tạo, ta dùng rcParams['pdf.fonttype']=42.

Các bước

  • Thiết lập kích thước hình và điều chỉnh khoảng đệm subplot.
  • Tạo figure mới.
  • Tạo điểm x, y bằng numpy.
  • Vẽ scatter x, y.
  • Đặt tiêu đề.
  • Lưu figure dạng pdf.

Ví dụ

import numpy as np
from matplotlib import pyplot as plt, font_manager as fm
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
plt.rcParams['pdf.fonttype'] = 42
fig, ax = plt.subplots()
x = np.random.rand(100)
y = np.random.rand(100)
ax.scatter(x, y, c=y, marker="v")
fprop = fm.FontProperties(fname=r'C:\Windows\Fonts\MISTRAL.TTF')
ax.set_title('Scatter Plot With Random Points',
              fontproperties=fprop, size=20, fontweight="bold")
plt.savefig("demo.pdf")

Kết quả

Khi chạy mã, biểu đồ sẽ được lưu trong thư mục dự án dưới tên "demo.pdf".

Cách nhúng font vào PDF do Matplotlib tạo?

Lưu ý kiểu font của tiêu đề. Tiêu đề được đặt bằng font Mistral.