使用 TTF 字体文件#

尽管明确指向单个 TTF 文件作为字体实例通常不是一个好主意,但你可以通过传入一个 pathlib.Path 实例作为 font 参数来做到这一点。请注意,将路径作为 str 传递是不受支持的,但你可以简单地根据需要将 str 包装在 pathlib.Path 中。

这里我们使用 Matplotlib 自带的 Computer Modern roman 字体(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()
This is a special font: cmr10.ttf

参考

本示例展示了以下函数、方法、类和模块的使用

由 Sphinx-Gallery 生成的画廊