【问题标题】:Matplotlib how to set legend's font typeMatplotlib 如何设置图例的字体类型
【发布时间】:2018-04-17 04:11:10
【问题描述】:

我想更改 Matplotlib 中图例文本的字体类型。我知道我可以这样做:

plt.legend(prop={'family': 'Arial'})

但是我想使用中文字体类型,我不知道我应该在上面的行中输入什么姓氏。但我确实有一个针对该中文字体类型的 fontproperties 对象。但是,我还没有找到设置图例字体属性的方法。

那么两个问题:

  1. 如何查找特定字体家族名称的名称
  2. 如何设置图例的字体属性

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    通过prop参数将FontProperties对象(例如下面的font)传递给ax.legend

    import matplotlib.pyplot as plt
    import numpy as np
    import matplotlib.font_manager as font_manager
    
    fig, ax = plt.subplots()
    x = np.linspace(-10, 10, 100)
    ax.plot(np.sin(x)/x, label='Mexican hat')
    
    font = font_manager.FontProperties(family='Comic Sans MS',
                                       weight='bold',
                                       style='normal', size=16)
    ax.legend(prop=font)
    plt.show()
    

    在 Ubuntu 上,您可以通过运行使新字体可用于您的系统

    fc-cache -f -v /path/to/fonts/directory
    

    我不确定它在其他操作系统上是如何完成的,或者fc-cache 在其他风格的 Unix 上的通用性如何。


    一旦你安装了你的字体以便你的操作系统知道它们,你可以通过删除~/.cache/fontconfig~/.cache/matplotlib中的文件来使matplotlib成为regenerate its fontList


    ~/.cache/matplotlib/fontList.json 文件为您提供了 matplotlib 知道的所有字体的可读列表。在那里,您会找到如下所示的条目:

    {
      "weight": "bold",
      "stretch": "normal",
      "fname": "/usr/share/fonts/truetype/msttcorefonts/Comic_Sans_MS_Bold.ttf",
      "_class": "FontEntry",
      "name": "Comic Sans MS",
      "style": "normal",
      "size": "scalable",
      "variant": "normal"
    },
    

    请注意,fname 是底层 ttf 文件的路径,并且还有一个 name 属性。你可以通过ttf文件的路径specify the FontProperties object

    font = font_manager.FontProperties(fname="/usr/share/fonts/truetype/msttcorefonts/Comic_Sans_MS_Bold.ttf")
    

    或按名称:

    font = font_manager.FontProperties(family='Comic Sans MS',
                                       weight='bold',
                                       style='normal', size=16)
    

    如果您不想在系统范围内安装您的字体,您可以通过fname 路径指定FontProperties 对象,从而绕过调用fc-cache 和搞乱~/.cache 的需要。

    【讨论】:

      猜你喜欢
      • 2012-09-06
      • 1970-01-01
      • 1970-01-01
      • 2014-09-01
      • 2015-10-03
      • 1970-01-01
      • 2014-03-22
      • 1970-01-01
      • 2012-04-30
      相关资源
      最近更新 更多