美文网首页Python中文python
matplotlib,seaborn中文乱码问题

matplotlib,seaborn中文乱码问题

作者: 小牛八卦 | 来源:发表于2016-09-16 22:16 被阅读5988次

在windows下面,matplotlib画图中文会显示乱码,主要原因是matplotlib默认没有指定中文字体。

有两种解决方案。

在画图的时候指定字体

import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=12)

plt.plot([1,2,3])
plt.title(u"测试",fontproperties=font)

测试中文字符.png

这种方法比较麻烦,每次画图的时候,都要指定字体位置。下面介绍一种一劳永逸的方法。

修改配置文件

  1. 将C:\Windows\Fonts 下面的字体 simsun.ttf,微软雅黑字体 拷贝到D:\Programs\Anaconda\Lib\site-packages\matplotlib\mpl-data\fonts\ttf 文件夹下。(Anaconda文件夹和安装位置有关)

  2. 用记事本打开D:\Programs\Anaconda\Lib\site-packages\matplotlib\mpl-data\matplotlibrc

找到如下两行:

#font.family         : sans-serif
#font.sans-serif     : Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif

去掉这两行前面的#,并且在font.sans-serif的冒号后面加上SimHei,结果如下所示

font.family         : sans-serif
font.sans-serif     : SimHei,Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif

重新启动python,matplotlib就可以输出中文字符了。

seaborn字体问题

上面的方法对于matplotlib是可以用的,但是如果引入了seaborn,就又会出现乱码,现在研究出来的方法是,在程序中加入以下代码

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

mac os x系统的乱码问题

修改配置文件的方法在mac os x 下面没有试验成功。
但可以用seaborn加代码的方式。或者对于matplotlib,加如下代码

from pylab import mpl
mpl.rcParams['font.sans-serif'] = ['SimHei'] # 指定默认字体
mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题

相关文章

网友评论

    本文标题:matplotlib,seaborn中文乱码问题

    本文链接:https://www.haomeiwen.com/subject/mnfiettx.html