Matplotlib如何设置图例的字体类型

时间:2017-11-04 15:50:22

标签: python matplotlib

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

df.iloc[:,cols] *=10

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

所以有两个问题:

  1. 如何查找特定字体姓氏的名称
  2. 如何设置图例的fontproperties

1 个答案:

答案 0 :(得分:5)

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

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()

enter image description here

在Ubuntu上,您可以通过运行

为系统提供新字体
fc-cache -f -v /path/to/fonts/directory

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

一旦安装了字体以便操作系统了解它们,您可以通过删除~/.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)

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