matplotlib,seaborn中文乱码问题的解决

方法一:指定字体

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

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

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

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

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

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

  

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

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

#font.family :sans-serif

#font.sans-serif:SimHei,……

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

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

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

 

猜你喜欢

转载自www.cnblogs.com/tongtong123/p/10672677.html