在Matplotlib中显示中文大多数人会推荐用SimHei,但是相应的英文奇丑无比。
经过试验,发现华文中宋是一个很好的字体。中文是宋体,英文基本是Times风格。
然后将这些文件拷贝到matplotlib的字体文件夹中。首先通过如下命令找到matplotlib的rc文件地址:1
2import matplotlib
print(matplotlib.matplotlib_fname())
rc所在目录下的font/ttf即是字体文件夹。
随后,删除matplotlib所建立的字体cache1
rm -rf ~/.cache/matplotlib
cache文件夹一般是~/.cache/matplotlib,具体的可能需要通过1
2import matplotlib
matplotlib.get_cachedir()
检查一下。
然后重开Python执行from matplotlib import pyplot as plt,matplotlib就会重建字体cache。
这时,打开cache文件下的fontlist-v330.json文件,使两个新加入的华文中宋字体具有相同的name键值,如:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20{
  "fname": "fonts/ttf/HuaWenSongTi-1.ttf",
  "name": "STSong",
  "style": "normal",
  "variant": "normal",
  "weight": 400,
  "stretch": "normal",
  "size": "scalable",
  "__class__": "FontEntry"
},
{
  "fname": "fonts/ttf/HuaWenZhongSong-Bold-1.ttf",
  "name": "STSong",
  "style": "normal",
  "variant": "normal",
  "weight": 700,
  "stretch": "normal",
  "size": "scalable",
  "__class__": "FontEntry"
}
name键值都设置成了STSong。
最后,更改rcParams采用STSong字体,完成目标:1
2from matplotlib import pyplot as plt
plt.rcParams["font.family"] = "STSong"
至于意义不明的"font.seris"之类的东西,则完全不用管。