matplotlib、seaborn中文显示问题

问题描述

在使用matplotlib(或seaborn)时,中文无法正常显示,显示结果为一个方框
环境:Windows+Anaconda


解决方法

方法一:设置plt的参数

plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号

另外:如果用了seaborn这样的基于matplotlib的库的话,需要额外设置:

sns.set(font='SimHei')

方法二:直接指定字体路径

import matplotlib.font_manager as fm
fonts = fm.FontProperties(fname=r'C:\Windows\Fonts\SimHei.ttf') # 设置字体
plt.xlabel(u'横轴',fontproperties=fonts)
plt.ylabel(u'纵轴',fontproperties=fonts)

方法三:手动修改matolotlib配置文件matplotlibrc

matplotlibrc的位置可用以下方式获得

import matplotlib
matplotlib.matplotlib_fname() #将会获得matplotlib包所在文件夹

1.打开matplotlibrc,分别找到以下项目,去掉前面的#注释

#font.serif          : DejaVu Serif, Bitstream Vera Serif, Computer Modern Roman, New Century Schoolbook, Century Schoolbook L, Utopia, ITC Bookman, Bookman, Nimbus Roman No9 L, Times New Roman, Times, Palatino, Charter, serif
#font.sans-serif     : SimHei, DejaVu Sans, Bitstream Vera Sans, Computer Modern Sans Serif, Lucida Grande, Verdana, Geneva, Lucid, Arial, 
#axes.unicode_minus  : False    ## use unicode for the minus symbol  用来正常显示负号

2.找到需要的中文字体,复制到fonts中的ttf目录下,位置在刚刚的matplotlibrc同一级文件夹中的fonts\ttf
3.将我们的字体文件的注册名字(如SimHei)加到配置文件项serif和sans-serif后面的第一个

#font.serif : SimHei, Bitstream Vera Serif, New Century Schoolbook, Century Schoolbook L, Utopia, ITC Bookman, Bookman, Nimbus Roman No9 L, Times New Roman, Times, Palatino, Charter, serif
#font.sans-serif     : SimHei, DejaVu Sans, Bitstream Vera Sans, Computer Modern Sans Serif, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif

4.到了这步应该就解决了,如果还是不能正常显示,可以在python中重新加载一下字体

from matplotlib.font_manager import _rebuild
_rebuild()    #重新加载一下
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值