如何在 Matplotlib 生成的 PDF 中嵌入字体
matplotlibpythondata visualization更新于 2025/7/6 2:20:17
要将字体嵌入 Matplotlib 生成的 PDF 中,我们可以使用 rc.Params['pdf.fonttype']=42。
步骤
- 设置图形大小并调整子图之间和周围的填充。
- 使用 figure() 方法创建新图形或激活现有图形。
- 使用 numpy 创建 x 和 y 数据点。
- 使用 scatter() 方法绘制 x 和 y 数据点。
- 设置图的标题。
- 将图形保存为 pdf格式。
示例
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='C:\Windows\Fonts\MISTRAL.TTF')
ax.set_title('带有随机点的散点图',
fontproperties=fprop, size=20, fontweight="bold")
plt.savefig("demo.pdf")
输出
当我们执行代码时,它会将以下图保存在项目目录中作为"demo.pdf"。

观察标题的字体样式。我们已将标题设置为 Mistral 字体
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

