一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

解决Matplotlib中文乱码问题

时间:2014-05-20 编辑:简简单单 来源:一聚教程网

.找到

 代码如下 复制代码


#font.family : sans-serif
去掉注释
2.找到


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


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

即去掉注释,并在配置值中添加 Microsoft YaHei ,
3.在windows下搜索msyh.ttf,即微软的雅黑字体,并将msyh.ttfcopy到python按照目录下的
x:/install_dir/Lib/site-packages/matplotlib/mpl-data/fonts/ttf
目录

其中x:/install_dir是python的安装目录
我在按上述操作的时候,遇到的问题:首先是在整个电脑全盘搜索都没有发现msyh.ttf文件,倒是将Microsoft YaHei UI 字体文件拷贝到python相应目录下的时候发现msyh.ttf,不过按照同样的方法,把fontlist.cache中对应的Microsoft YaHei的值改为msyh.ttc也是徒劳。把msyh.ttc拷贝到python路径下的ttf文件夹下也是不行。后来,有尝试使用楷体的ttf文件:在fontlist.cache中搜索楷体ttf文件对应的变量名‘KaiTi’,然后在也是按照上述的步骤操作,在matplotlibrc中修改也是徒劳。

下面是另一种方法:( 解决matplotlib图像中文显示问题 )

1. 找到matplotlib安装目录,比如C:\Development\python26\Lib\site-packages\matplotlib\mpl-data目录下的matplotlibrc文件,找到#font.sans-serif : …这一行,把后面的修改为’nothing’,这样做是强制让系统无法找到英文字体,而是用matplotlib默认字体Vera.ttf替换 ( 不做这一步,我测试了也是可以的! )

 代码如下 复制代码


#font.sans-serif : nothing

2. 同个文件中找到#verbose.level : silent这行。把silent修改为debug,这样做是为了看更详细的输出.( 不做这一步,我测试了也是可以的 !)

 

 代码如下 复制代码
#verbose.level : debug

3. 找到字体目录C:\Development\python26\Lib\site-packages\matplotlib\mpl-data\fonts\ttf下的Vera.ttf。这里我们用中文楷体可以从windows/system32/fonts拷贝过来,直接张贴到前面的ttf目录下,然后更名为Vera.ttf,相当于用中文的字体替换掉之前的英文字体,偷龙转凤!!
4. 程序中指定文件编码# -*- coding: utf-8 -*- ,并且确保要输出的中文是unicode形式,检查是否为unicode代码:isinstance(s, unicode)。
上述操作,其实只要将Vera.ttf文件替换掉即可,不用修改matplotlibrc文件也是可行的。只是担心以后会有什么副作用。。。


再整理一种办法

1.修改matplotlibrc文件

进入Python安装目录下的Lib\site-packages\matplotlib\mpl-data目录,打开matplotlibrc文件,删除font.family和font.sans-serif两行前的#,并在font.sans-serif后添加微软雅黑字体(Microsoft YaHei),代码如下:

matplotlibrc文件修改Python

 代码如下 复制代码

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

 
2.代码中别忘了unicode编码

matplotlib 示例代码Python

 代码如下 复制代码

import matplotlib.pyplot as plt
 
plt.clf()  # 清空画布
plt.plot([1, 2, 3], [4, 5, 6])
plt.xlabel(u"横轴")
plt.ylabel(u"纵轴")
plt.title("pythoner.com")matplotlib示例
plt.show()

热门栏目