【问题标题】:How to use a (random) *.otf or *.ttf font in matplotlib?如何在 matplotlib 中使用(随机)*.otf 或 *.ttf 字体?
【发布时间】:2011-12-05 07:49:13
【问题描述】:

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

【问题讨论】:

    标签: python matplotlib fonts


    【解决方案1】:

    在此处查看示例: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()
    

    【讨论】:

    • 它对我不起作用(Python 3.6),如果无法识别字体,它只会使用默认字体
    【解决方案2】:

    在 *nix 上,您可以通过启用 matplotlib 的 fontconfig 后端来使用所有系统字体。

    但是 matplotlib 并没有真正与 fontconfig 库对话,它通过运行 fontconfig cli 实用程序来模拟其行为。

    因此,核对 matplotlib fontconfig 缓存以便它发现新字体可以成为救命稻草(这个缓存的存在直接证明了缺乏完整的 fontconfig 集成)。

    【讨论】:

    • 可能这并不能回答问题,但是您挽救了我最后的理智。谢谢。没有应用新的系统字体,所以我只删除了这些文件夹:~/.matplotlib、~/.cache/matplotlib、~/.cache/fontconfig 一定要重新启动你的 python 环境。
    • 感谢您指出缓存位置。为我工作。
    【解决方案3】:

    您也可以在 matplot 配置中指定字体并覆盖默认字体系列,例如对于 *nix

    ~/.matplotlib/matplotlibrc

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

    【讨论】:

      猜你喜欢
      • 2014-07-23
      • 2011-07-15
      • 2016-03-22
      • 2013-05-23
      • 2021-06-08
      • 2014-06-04
      • 2012-03-08
      • 1970-01-01
      • 2017-02-02
      相关资源
      最近更新 更多