备注
前往末尾 下载完整示例代码。
使用 ttf 字体文件#
虽然通常不建议为字体实例显式指向单个 ttf 文件,但你可以通过传递 pathlib.Path 实例作为 font 参数来实现。请注意,不支持将路径作为 str 传递,但你可以根据需要在 pathlib.Path 中包装 str。
在这里,我们使用了 Matplotlib 附带的 Computer Modern 罗马字体 (cmr10)。
对于更灵活的解决方案,请参阅 配置字体族 和 字体演示(面向对象风格)。
from pathlib import Path
import matplotlib.pyplot as plt
import matplotlib as mpl
fig, ax = plt.subplots()
fpath = Path(mpl.get_data_path(), "fonts/ttf/cmr10.ttf")
ax.set_title(f'This is a special font: {fpath.name}', font=fpath)
ax.set_xlabel('This is the default font')
plt.show()