如何在matplotlib中使用(随机的)*.otf或*.ttf字体?

49

我如何在所有matplotlib图中使用计算机上我的字体库中的任何类型的字体(例如*otf*ttf)?

4个回答

75

请查看这里的示例: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()

输入图像描述


4
对我来说(Python 3.6),它无法工作,如果字体无法识别,它只会使用默认字体。 - irenemeanspeace

3
在*nix系统上,您可以通过启用matplotlib的fontconfig后端来使用所有系统字体。
然而,matplotlib并没有直接与fontconfig库交互,而是通过运行fontconfig cli实用程序来模拟其行为。
因此,清除matplotlib fontconfig缓存以发现新字体可能会拯救生命(这个缓存的存在直接证明了缺乏完整的fontconfig集成)。

2
也许这并不是回答问题的方法,但你拯救了我最后一点理智。谢谢。一个新的系统字体没有被应用,所以我只删除了这些文件夹:~/.matplotlib, ~/.cache/matplotlib, ~/.cache/fontconfig请确保重新启动您的Python环境。 - Mateo de Mayo
谢谢你指出缓存位置,对我很有帮助。 - Tyreal

1
以下是一个示例,说明如何将任何OTF/TTF文件设置为Mathplotlib的默认字体。这样一来,您就不需要将字体作为参数传递给每个图形。
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(),
    })
    

完整代码


0

您可以在Matplotlib配置中指定字体并覆盖默认字体系列,例如,在*nix系统中。

~/.matplotlib/matplotlibrc

font.family: sans-serif
font.sans-serif: your font,sans-serif

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接