我如何在所有matplotlib
图中使用计算机上我的字体库中的任何类型的字体(例如*otf
或*ttf
)?
我如何在所有matplotlib
图中使用计算机上我的字体库中的任何类型的字体(例如*otf
或*ttf
)?
请查看这里的示例:http://matplotlib.sourceforge.net/examples/api/font_file.html
通常情况下,如果您想要使用特定的.ttf
文件,可以像这样操作。(请记住,指向特定字体文件通常是一个不好的主意!)
import matplotlib.font_manager as fm
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(range(10))
prop = fm.FontProperties(fname='/usr/share/fonts/truetype/groovygh.ttf')
ax.set_title('This is some random font', fontproperties=prop, size=32)
plt.show()
通常情况下,您只需指定字体名称,让 matplotlib 负责查找具体的文件。例如:
import matplotlib.pyplot as plt
plt.plot(range(10))
plt.title('This is some random font', family='GroovyGhosties', size=32)
plt.show()
如果你想让matplotlib始终使用特定的字体,那么请自定义你的.matplotlibrc
文件(你需要设置font.family
参数,注意应该指定字体名称而不是.ttf文件的路径)。.matplotlibrc
文件):import matplotlib as mpl
mpl.rcParams['font.family'] = 'GroovyGhosties'
import matplotlib.pyplot as plt
plt.plot(range(10))
plt.title('Everything is crazy!!!', size=32)
plt.show()
import os
import matplotlib
import matplotlib.font_manager as font_manager
def load_matplotlib_local_fonts():
# Load a font from TTF file,
# relative to this Python module
# https://dev59.com/91sV5IYBdhLWcg3w4iL-#69016300
font_path = os.path.join(os.path.dirname(__file__), 'Humor-Sans.ttf')
assert os.path.exists(font_path)
font_manager.fontManager.addfont(font_path)
prop = font_manager.FontProperties(fname=font_path)
# Set it as default matplotlib font
matplotlib.rc('font', family='sans-serif')
matplotlib.rcParams.update({
'font.size': 16,
'font.sans-serif': prop.get_name(),
})
完整代码。
您可以在Matplotlib配置中指定字体并覆盖默认字体系列,例如,在*nix系统中。
~/.matplotlib/matplotlibrc
font.family: sans-serif
font.sans-serif: your font,sans-serif