您的位置:首页 > 编程语言 > PHP开发

¥¥%%%%%Ubuntu下用matplotlib作图时显示中文###重点第5条可以用!!!!%%%%%

2017-04-24 19:37 666 查看

Ubuntu下用matplotlib作图时显示中文

之前在Ubuntu下用matplotlib作图的时候发现无法正常显示中文,查了一番以后发现是Ubuntu系统和matplotlib库没有共同可显示的中文字体库的原因。用此文章的方法可以解决这一问题。

1.首先需要安装中文字体

git clone https://github.com/tracyone/program_font && cd program_font && ./install.sh

PS:文章中说需要删除matplotlib的缓存列表
~/.cache/matplotlib/fontList.py3k.cache
,但是在下并没有删,可能是这个原因导致之后文中的调用方法并没有起效而是换了一种。

2.将安装的ttf字体文件复制到matplotlib的字体文件夹中(安装的ttf文件一般在/use/share/fonts/MyFonts/目录下)

用matplotlib.matplotlib_fname()命令可以获取matplotlib的字体配置文件。比如在下的在如下位置
/home/MyUserName/anaconda2/envs/tensorflow/lib/python2.7/site-packages/matplotlib/mpl-data/matplotlibrc
.那么相应的字体目录在
mpl-data/fonts/ttf
下。

cp /use/share/fonts/MyFonts/*.ttf /your/path/to/mpl-data/fonts/ttf/

3.寻找matplotlib和Ubuntu都能用的中文字体 (原文源代码)

__author__ = 'Katherine'
from matplotlib.font_manager import FontManager
import subprocess

fm = FontManager()
mat_fonts = set(f.name for f in fm.ttflist)

output = subprocess.check_output(
'fc-list :lang=zh -f "%{family}\n"', shell=True)
output = output.decode('utf-8')
# print '*' * 10, '系统可用的中文字体', '*' * 10
# print output
zh_fonts = set(f.split(',', 1)[0] for f in output.split('\n'))
available = mat_fonts & zh_fonts

print('*' * 10, '可用的字体', '*' * 10)
for f in available:
print(f)


输出为(基本是刚安装的中文字体):

********** 可用的字体 **********
YouYuan
SimHei
YaHei Consolas Hybrid
FangSong
KaiTi
Microsoft YaHei
LiSu
Yahei Mono

4.配置matplotlib字体文件

上面提到字体文件为matplotlibrc文件,编辑此文件找到font.family, font.serif, font.sans-serif行,删除句首#,然后将上述可用字体添加进去并用 , 隔开。例如:font.family: YouYuan, SimHei, FangSong, ...

5.脚本中进行申明

import pylab import mpl
mpl.rcParams['font.sans-serif'] = ['SimHei'] #指定默认字体,但在下运行的时候报了warning并没正常显示中文


改用此方法则可行:

from matplotlib.font_manager import FontProperties
chinese_font = FontProperties(fname='/usr/share/fonts/MyFonts/YaHei.Consolas.1.11b.ttf')
...
plt.text(x, y, display, fontsize=12, fontproperties=chinese_font)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: