Matplot中文乱码完美解决方案

来源:互联网 发布:淘宝上真正的原单店 编辑:程序博客网 时间:2024/05/22 13:52

一、修改matplotlibrc文件 (永久解决方案)

1. 定位matplotlibrc文件

该文件位于[python_install_dir]\Lib\site-packages\matplotlib\mpl-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]\.matplotlib\fontList.cache 中存储的映射关系找到字体文件所在的位置。fontList.cache 文件部分内容如下所示:

S'Microsoft YaHeip147sg16I700sg17g13sg18g13sg19S'C:\\Windows\\Fonts\\msyhbd.ttf'

Microsoft YaHei字体默认的位置位于 C:\Windows\Fonts\ 目录下。

注意:如果第三步操作完之后仍不起作用,可以将 C:\Windows\Fonts\ 目录下的Microsoft YaHei字体文件拷贝到 [python_install_dir]\Lib\site-packages\matplotlib\mpl-data\fonts\ttf\ 目录下

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

0 0