之前用的SimHei字体,运行后报错findfont: Font family [‘sans-serif’] not found
查资料后发现是SimHei字体不支持,有些文章提供的解决方法是下载SimHei字体。
后来发现其实不用这么麻烦,只要选择支持的自带中文字体就可以了。
第一步:
找到matplotlib的配置文件路径:
import matplotlib
print(matplotlib.matplotlib_fname())
文件路径为:
/Users/***/anaconda/envs/Python3/lib/python3.6/site-packages/matplotlib/mpl-data/matplotlibrc
第二步:
在终端中修改配置文件:
vim /Users/***/anaconda/envs/Python3/lib/python3.6/site-packages/matplotlib/mpl-data/matplotlibrc
找到下面两行,去掉前面的#号,保存:
#font.family : sans-serif
#font.sans-serif : DejaVu Sans, Bitstream Vera Sans, Computer Modern Sans Serif, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif
第三步:
运行下面这段代码,显示所有支持的字体:
import matplotlib
a=sorted([f.name for f in matplotlib.font_manager.fontManager.ttflist])
for i in a:
print(i)
第四步:
比如我选的是Heiti TC,将字体设置为Heiti TC:
plt.rcParams['font.family']='sans-serif'
plt.rcParams['font.sans-serif'] = ['Heiti TC']
然后就OK啦!