使用 ttf 字體檔案#

儘管直接指向字體實例的單個 ttf 檔案通常不是一個好主意,但您仍然可以透過傳遞一個 pathlib.Path 實例作為 font 參數來做到。請注意,有意不支援將路徑作為 strs 傳遞,但您只需要將 strs 包裝在 pathlib.Paths 中即可。

在這裡,我們使用 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 產生的圖庫