Skip to content

Instantly share code, notes, and snippets.

@luw2007
Last active December 30, 2015 23:59
Show Gist options
  • Save luw2007/7904664 to your computer and use it in GitHub Desktop.
Save luw2007/7904664 to your computer and use it in GitHub Desktop.
matplotlib 支持 ttc . 原理为修改matplotlib 的 字体查找函数, 让其可以查找ttc 字体.

#matplotlib 支持 ttc ttc 是 microsoft 的标准, 还是建议使用 ttctools 分解 ttc 为多个ttf . 然后拷贝ttf 到字体目录(/usr/share/fonts/truetype)

grep Wen ~/.cache/matplotlib/fontList.cache
S'WenQuanYi Micro Hei'

以下为hack方法, 不建议使用

matplotlib 1.3.1 版本中默认不使用ttc 字体, hack matplotlib的字体查找方法, 使其可以使用ttc 字体. ##安装字体 安装 文泉驿中文字体, ubuntu 中包名 ttf-wqy-microhei, 也可以安装其他字体.

apt-get install ttf-wqy-microhei    

##配置文件 复制配置文件

cat <<EOF > ~/.config/matplotlib/matplotlibrc 
backend      : agg
verbose.level: debug
font.sans-serif: WenQuanYi Micro Hei #可以换成其他已经安装的中文字体名称
axes.unicode_minus  : False
EOF

注: 1.3.1版本配置文件 ~/.config/matplotlib/matplotlibrc, 字体缓存文件 ~/.cache/matplotlib/fontList.cache; 1.1.1rc版本为 ~/.matplotlib/matplotlibrc 和 ~/.matplotlib/fontList.cache

执行

python -c "import os, pylab, matplotlib; pylab.title(U'中文'); pylab.savefig('/tmp/1.png'); print '\n\n#config file: %s\n#module path: %s\n#cache file:%s/fontList.cache' % (matplotlib.matplotlib_fname(),  os.path.split(matplotlib.__file__)[0],matplotlib.get_cachedir())"

确认"#config file" 配置文件是否正确, 并记录 "#module path:"( 以下使用 /usr/local/lib/python2.7/dist-packages/matplotlib) 和 "#cache file" (以下使用 ~/.cache/matplotlib/fontList.cache) 的值, 下面要用到.

##使matplotlib 支持 ttc 编辑 "#module path:" 目录中的 font_manager.py vim /usr/local/lib/python2.7/dist-packages/matplotlib/font_manager.py +161 161 行: return {'ttf': ('ttf', 'otf'),return {'ttf': ('ttf', 'otf', 'ttc'),

注: 1.3.1 为161行, 1.1.1rc 为 159行 ##验证

rm ~/.cache/matplotlib/fontList.cache
python -c "import matplotlib; print matplotlib.matplotlib_fname()"
grep ttc ~/.cache/matplotlib/fontList.cache
python -c "import pylab; pylab.title(U'中文'); pylab.savefig('/tmp/1.png')"

检查输出中的"findfont: Matching :family" 是否为你设置的中文字体

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment