设置matplotlib中文显示(宋体) 您所在的位置:网站首页 matplotlib不显示汉字 设置matplotlib中文显示(宋体)

设置matplotlib中文显示(宋体)

2023-01-30 20:19| 来源: 网络整理| 查看: 265

记录设置 matplotlib中文显示,免得下次就忘了

环境:win7 64, Anaconda,Python3.5.2,matplotlib1.5.3

最近折腾了一会儿iPython,想学学用matplotlib作图,遂安装了Anaconda。不料matplotlib对中文支持不好,默认情况下没有中文字体,打出来一堆□□。咋解决呢?baidu,Google一起上呗,结果并不能让人满意,不过还是学到基本设置都在MATPLOTLIBRC文件中。

MATPLOTLIBRC位置:INSTALL\Lib\site-packages\matplotlib\mpl-data\

其中### FONT部分包括以下设置,其中serif, sans-serif, cursive, fantasy, monospace是matplotlib的五种font.family

#font.serif : simsun, ...#font.sans-serif :simhei, ...#font.cursive : ...#font.fantasy : ...#font.monospace : ...

将simsun(宋体),simhei(黑体)添加到对应的serif和sans-serif里面,保存。

此时可以正确显示中文黑体,但是宋体仍然不行。

再打开INSTALL\Lib\site-packages\matplotlib\font_manager.py 进行编辑

在大约155-162行,如下,

def get_fontext_synonyms(fontext): """ Return a list of file extensions extensions that are synonyms for the given file extension *fileext*. """ return {'ttf': ('ttf', 'otf'), 'otf': ('ttf', 'otf'), 'afm': ('afm',)}[fontext]

这部分用来识别字体的扩展名,由于simsun等某些中文字体扩展名是ttc,所以没办法被matplotlib识别加载,将部分略作修改后保存即可。

return {'ttf': ('ttf', 'otf'), ...

修改为

return {'ttf': ('ttf', 'otf', 'ttc'), ...

另外可能有必要清理掉系统盘中Users\YOURNAME\.matplotlib\下的缓存文件fontList.py3k.cache

然后打开

ipython --pylabimport matplotlib.pyplot as pltrc('font',**{'family':'sans-serif','sans-serif':['simsun']})plt.title(u'中文')plt.text(.2,.8,u'这也是中文',fontsize=40)

可正常显示中文其他windows所用字体在系统的Windows\Fonts\注意:只测试了黑体和宋体,并未测试其他字体。



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有