註解
跳至結尾以下載完整範例程式碼。
使用 ttf 字體檔案#
儘管直接指向字體實例的單個 ttf 檔案通常不是一個好主意,但您仍然可以透過傳遞一個 pathlib.Path
實例作為 font 參數來做到。請注意,有意不支援將路徑作為 str
s 傳遞,但您只需要將 str
s 包裝在 pathlib.Path
s 中即可。
在這裡,我們使用 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()
