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

9cbw7uwe  于 12个月前  发布在  其他
关注(0)|答案(4)|浏览(114)

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

8yoxcaq7

8yoxcaq71#

请参见此处的示例: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总是使用特定的字体,那么customize your .matplotlibrc file。(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()

pvabu6sv

pvabu6sv2#

在 *nix上,您可以通过启用matplotlib的fontconfig后端来使用所有系统字体。
然而,matplotlib并不真正与fontconfig库对话,它通过运行fontconfig工具来模拟它的行为。
因此,破坏matplotlib fontconfig缓存,让它发现新字体可能是一个救星(这个缓存的存在直接证明了缺乏完整的fontconfig集成)。

gjmwrych

gjmwrych3#

下面是一个如何将任何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://stackoverflow.com/a/69016300/315168
    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(),
    })

Full code

5cnsuln7

5cnsuln74#

您可以指定字体并覆盖matplot配置中的默认字体系列,例如 *nix
matplotlib/matplotlibrc

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

相关问题