【问题标题】:How to load .ttf file in matplotlib using mpl.rcParams?如何使用 mpl.rcParams 在 matplotlib 中加载 .ttf 文件?
【发布时间】:2013-05-10 14:33:08
【问题描述】:

我有一个启动的 matplotlib 脚本...

import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm

mpl.rcParams['xtick.labelsize']=16 
...

我用过命令

fm.findSystemFonts()

获取我系统上的字体列表。我发现了我想使用的 .ttf 文件的完整路径,

'/usr/share/fonts/truetype/anonymous-pro/Anonymous Pro BI.ttf'

我尝试使用以下命令使用此字体,但没有成功

mpl.rcParams['font.family'] = 'anonymous-pro'  

mpl.rcParams['font.family'] = 'Anonymous Pro BI'

两者都返回类似

/usr/lib/pymodules/python2.7/matplotlib/font_manager.py:1218: UserWarning: findfont: Font family ['anonymous-pro'] not found. Falling back to Bitstream Vera Sans

我可以使用 mpl.rcParams 字典在我的绘图中设置此字体吗?

编辑

阅读更多内容后,似乎这是从 .ttf 文件中确定字体系列名称的一般问题。这在 linux 或 python 中容易做到吗?

另外,我试过添加

mpl.use['agg']
mpl.rcParams['text.usetex'] = False

没有成功

【问题讨论】:

    标签: python fonts matplotlib


    【解决方案1】:

    指定字体系列:

    如果您只知道 ttf 的路径,那么您可以使用 get_name 方法发现字体系列名称:

    import matplotlib as mpl
    import matplotlib.pyplot as plt
    import matplotlib.font_manager as font_manager
    
    path = '/usr/share/fonts/truetype/msttcorefonts/Comic_Sans_MS.ttf'
    prop = font_manager.FontProperties(fname=path)
    mpl.rcParams['font.family'] = prop.get_name()
    fig, ax = plt.subplots()
    ax.set_title('Text in a cool font', size=40)
    plt.show()
    

    通过路径指定字体:

    import matplotlib.pyplot as plt
    import matplotlib.font_manager as font_manager
    
    path = '/usr/share/fonts/truetype/msttcorefonts/Comic_Sans_MS.ttf'
    prop = font_manager.FontProperties(fname=path)
    fig, ax = plt.subplots()
    ax.set_title('Text in a cool font', fontproperties=prop, size=40)
    plt.show()
    

    【讨论】:

    • 谢谢。我在 [this](stackoverflow.com/questions/12790284/…) 帖子中看到了该解决方案。但是,我想更改绘图上所有文本的字体,而不更新每个生成文本的命令和/或添加命令来更改轴标签的文本。这就是为什么我更喜欢使用 mpl.rcParams 如果可能的话。
    • 酷。感谢您的详细回答。很有帮助!
    • 有没有办法将此路径或具有多个 .ttf 文件的本地目录的路径添加到我的 matplotlibrc 文件中的变量或其他东西中,这样我就不必重新输入路径每次我想使用 matplotlib 否则找不到的字体?
    【解决方案2】:

    您可以使用 fc-query myfile.ttf 命令根据 Linux 字体系统(fontconfig)查看字体的元数据信息。它应该打印你的名字 matplotlib 将接受。然而,matplotlib fontconfig 的集成现在相当部分,所以我担心你很可能会遇到其他 Linux 应用程序中相同字体不存在的错误和限制。

    (这种悲伤的状态被 matplotlib 的默认配置中的所有硬编码字体名称隐藏,一旦你开始尝试更改它们,你就处于危险的境地)

    【讨论】:

      【解决方案3】:

      我把它写到了不到 100 行,@nim 这也更详细地解释了它有多危险,一些修改完全改变了字体属性和字体大小的行为。

      先决条件:Matplotlib和包含ttf字体文件calibri.ttf的脚本同级字体文件夹

      但这就是我给你的复活节彩蛋:

      import os
      import matplotlib
      import matplotlib.pyplot as plt
      import matplotlib.font_manager as fm
      from matplotlib import ft2font
      from matplotlib.font_manager import ttfFontProperty
      
      __font_dir__ = os.path.join(os.path.dirname(__file__),"font")
      fpath = os.path.join(__font_dir__,'calibri.ttf')
      
      font = ft2font.FT2Font(fpath)
      fprop = fm.FontProperties(fname=fpath)
      
      ttfFontProp = ttfFontProperty(font)
      
      fontsize=18
      
      fontprop = fm.FontProperties(family='sans-serif',
                                  #name=ap.fontprop.name,
                                  fname=ttfFontProp.fname,
                                  size=fontsize,
                                  stretch=ttfFontProp.stretch,
                                  style=ttfFontProp.style,
                                  variant=ttfFontProp.variant,
                                  weight=ttfFontProp.weight)
      
      matplotlib.rcParams.update({'font.size': fontsize,
                              'font.family': 'sans-serif'})
      
      fig, axis = plt.subplots()
      
      axis.set_title('Text in a cool font',fontsize=fontsize,fontproperties=fontprop)
      
      ax_right = axis.twinx()
      
      axis.set_xlabel("some Unit",fontsize=fontsize,fontproperties=fontprop)
      
      leftAxesName,rightAxesName = "left Unit", "right Unit"
      
      axis.set_ylabel(leftAxesName,fontsize=fontsize,fontproperties=fontprop)
      if rightAxesName:
          ax_right.set_ylabel(rightAxesName,fontsize=fontsize,fontproperties=fontprop)
      
      for xLabel in axis.get_xticklabels():
          xLabel.set_fontproperties(fontprop)
          xLabel.set_fontsize(fontsize)
      
      for yLabel in axis.get_yticklabels():
          yLabel.set_fontproperties(fontprop)
          yLabel.set_fontsize(fontsize)    
      
      yTickLabelLeft = ax_right.get_yticklabels()
      
      for yLabel in yTickLabelLeft:
          yLabel.set_fontproperties(fontprop)
          yLabel.set_fontsize(fontsize)
      
      axis.plot([0,1],[0,1],label="test")
      
      nrow,ncol=1,1
      handels,labels= axis.get_legend_handles_labels()
      
      propsLeft=axis.properties()
      
      propsRight=ax_right.properties()
      
      print(propsLeft['title'],propsLeft['xlabel'],propsLeft['ylabel'])
      print(propsRight['ylabel'])
      
      fig.set_tight_layout({'rect': [0, 0, 1, 0.95], 'pad': 0.05, 'h_pad': 1.5})
      fig.tight_layout()
      fig.set_alpha(True)
      
      leg_fig = plt.figure()
      
      leg = leg_fig.legend(handels, labels, #labels = tuple(bar_names)
         ncol=ncol, mode=None, 
         borderaxespad=0.,
         loc='center',        # the location of the legend handles
         handleheight=None,   # the height of the legend handles
         #fontsize=9,         # prop beats fontsize
         markerscale=None,
         frameon=False,
         prop=fontprop)
      
      plt.show()
      

      【讨论】:

        猜你喜欢
        • 2011-02-11
        • 2011-10-27
        • 1970-01-01
        • 1970-01-01
        • 2011-12-05
        • 2017-11-28
        • 2017-02-08
        • 2020-12-06
        • 2016-11-26
        相关资源
        最近更新 更多