通过prop参数将FontProperties对象(例如下面的font)传递给ax.legend:
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.font_manager as font_manager
fig, ax = plt.subplots()
x = np.linspace(-10, 10, 100)
ax.plot(np.sin(x)/x, label='Mexican hat')
font = font_manager.FontProperties(family='Comic Sans MS',
weight='bold',
style='normal', size=16)
ax.legend(prop=font)
plt.show()
在 Ubuntu 上,您可以通过运行使新字体可用于您的系统
fc-cache -f -v /path/to/fonts/directory
我不确定它在其他操作系统上是如何完成的,或者fc-cache 在其他风格的 Unix 上的通用性如何。
一旦你安装了你的字体以便你的操作系统知道它们,你可以通过删除~/.cache/fontconfig和~/.cache/matplotlib中的文件来使matplotlib成为regenerate its fontList。
~/.cache/matplotlib/fontList.json 文件为您提供了 matplotlib 知道的所有字体的可读列表。在那里,您会找到如下所示的条目:
{
"weight": "bold",
"stretch": "normal",
"fname": "/usr/share/fonts/truetype/msttcorefonts/Comic_Sans_MS_Bold.ttf",
"_class": "FontEntry",
"name": "Comic Sans MS",
"style": "normal",
"size": "scalable",
"variant": "normal"
},
请注意,fname 是底层 ttf 文件的路径,并且还有一个 name 属性。你可以通过ttf文件的路径specify the FontProperties object:
font = font_manager.FontProperties(fname="/usr/share/fonts/truetype/msttcorefonts/Comic_Sans_MS_Bold.ttf")
或按名称:
font = font_manager.FontProperties(family='Comic Sans MS',
weight='bold',
style='normal', size=16)
如果您不想在系统范围内安装您的字体,您可以通过fname 路径指定FontProperties 对象,从而绕过调用fc-cache 和搞乱~/.cache 的需要。