关于mac matplotlib中文字符乱码问题

我在网上收集了一些资料,但是好多都无法起作用。直到我搜到这个博客
为了以后方便查找,现记录一下。
第一步下载字体:SimHei
第二步将字体拷贝到matplotlib字体库中。

import matplotlib as mlp
mlp.matplotlib_fname()
'/Users/apple/anaconda3/envs/py35/lib/python3.5/site-packages/matplotlib/mpl-data/matplotlibrc'

字体路径就在”*/python3.5/site-packages/matplotlib/mpl-data/fonts/ttf”
将下载好的字体拷贝到该字体路径中。
第三步修改matplotlib的配置文件,即”*/python3.5/site-packages/matplotlib/mpl-data/matplotlibrc”文件

根据实际情况修改,找到如下两项,去掉前面的#,并在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

同时将找到axes.unicode_minus,将True改为False,作用就是解决负号’-‘显示为方块的问题

在网上一般都是上面三个步骤,但是不一定能成功,还需要去掉matplotlib的缓存文件
第四步:去掉matplotlib的缓存文件

rm -rf ~/.matplotlib/*.cache

第五步:matplotlib不会每次启动时都重新扫描所有的字体文件并创建字体索引列表,因此在复制完字体文件之后,需要运行下面的语句以重新创建字体索引列表,下面这个语句只需执行一次就行了。以后就一劳永逸,不用再执行。

import matplotlib as mpl
from matplotlib.font_manager import _rebuild
_rebuild()
#防止中文乱码问题
mpl.rcParams['font.sans-serif']=[u'SimHei']
mpl.rcParams['axes.unicode_minus']=False

猜你喜欢

转载自blog.csdn.net/sc_lujun/article/details/80824857