Matplot中文乱码完美解决方式

一、改动matplotlibrc文件 (永久解决方式)

1. 定位matplotlibrc文件

该文件位于[python_install_dir]Libsite-packagesmatplotlibmpl-data文件夹下。

2. 改动matplotlibrc文件内容。

matplotlibrc文件部分内容例如以下:

font.family         : sans-serif        #默认情况下。该字段为关闭状态。去掉凝视就可以。
font.sans-serif     : Microsoft YaHei , Bitstream Vera Sans, 
                      Lucida Grande, Verdana, Geneva, Lucid,
                      Arial, Helvetica, Avant Garde,
                      sans-serif        #加入"Microsoft YaHei"

font.sans-serif中加入 Mircosoft YaHei 之后,matplot 通过 C:Users[your_account].matplotlibfontList.cache 中存储的映射关系找到字体文件所在的位置。

fontList.cache 文件部分内容例如以下所看到的:

S'Microsoft YaHei
p147
sg16
I700
sg17
g13
sg18
g13
sg19
S'C:\Windows\Fonts\msyhbd.ttf'

Microsoft YaHei字体默认的位置位于 C:WindowsFonts 文件夹下。

注意:假设第三步操作完之后仍不起作用,能够将 C:WindowsFonts 文件夹下的Microsoft YaHei字体文件复制到 [python_install_dir]Libsite-packagesmatplotlibmpl-datafonts tf 文件夹下

3. 重建字体索引列表。

matplotlib不会每次启动时都又一次扫描全部的字体文件并创建字体索引列表,因此在复制完字体文件之后。须要执行以下的语句以又一次创建字体索引列表 ,须要在console中执行以下代码:

>>>from matplotlib.font_manager import _rebuild`
>>>_rebuild()

二、在py文件里显式载入字体 (暂时解决方式)

1. 显示载入matplotlib的字体管理器,代码例如以下:

    # 载入自己定义字体
    # fname 为字体文件路径
    import matplotlib
    myfont = matplotlib.font_manager.FontProperties(fname=r'C:/Windows/Fonts/msyh.ttf')
     ...
    # 在须要显示汉字的地方,指定自己定义字体就可以
    plt.xlabel(u'汉字',  fontproperties=myfont)
    plt.xlabel(u'汉字',  fontproperties=myfont)
    ...

參考文献
http://hyry.dip.jp/tech/book/page/scipy/matplotlib_fast_plot.html#id6

原文地址:https://www.cnblogs.com/bhlsheji/p/5349786.html