方法一:指定字体

import matplotlib.pyplot as plt

myfont = matplotlib.font_manager.FontProperties(fname='/home/dai/SimHei.ttf')  

plt.plot([0, 1], [1, 2])
plt.title('显示中文', size=16, fontproperties=myfont)  #在每一个需要显示中文的地方指定字体

matplotlib,seaborn中文乱码问题的解决 随笔 第1张

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

这种方法比较麻烦,每次画图都需要指定字体

 

方法二:添加字体到matplotlib

1)找到matplotlib的配置文件位置

matplotlib,seaborn中文乱码问题的解决 随笔 第2张

matplotlib字体库的位置为/usr/local/lib/python3.6/dist-packages/matplotlib/mpl-data/fonts/ttf

2)找到合适的字体放入matplotlib字体库中,如:SimHei.ttf

matplotlib,seaborn中文乱码问题的解决 随笔 第3张

3)删除~/.cache/matplotlib/fontList.json,重启python,会重新生成~/.cache/matplotlib/fontList.json,(或者是其他名字的json文件)

打开该文件,查看是否加载了新加的字体;

  matplotlib,seaborn中文乱码问题的解决 随笔 第4张

4)打开1)中matplotlib配置文件matplotlibrc

找到以下两行取消注释,把“SimHei”加到第一个位置上

#font.family :sans-serif

#font.sans-serif:SimHei,……

matplotlib,seaborn中文乱码问题的解决 随笔 第5张

翻来覆去弄了好久,不行就重启试试。。。

如果还要使用seaborn,添加以下代码就OK了

import seaborn as sns
sns.set_style({'font.sans-serif':['SimHei','Arial']})

 

 

 

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄