ubuntu下matplotlib中文字体的设置

时间:2021-08-23 23:39:47

置方法主要参考http://blog.sciencenet.cn/blog-43412-343002.html中的第一种方法,第二种方法在ubuntu中怎么设置都没有用。。。
如果有人在ubuntu 15.04成功使用第二种方法解决了,还请不吝赐教发送邮件

安装matplotlib时,我采用的是直接使用下面的apt命令进行安装:
sudo apt-get install python-matplotlib
安装出来的东西,与网上设置中文字体遇到环境有很大不同。
1. mpl-data安装目录不同,该目录存放有matplotlib使用的字体,在ubuntu下目录位于/usr/share/matplotlib;
2. matplotlibrc目录不同,位于/etc/matplotlibrc;
3. 在ubuntu下家目录下默认配置文件存放在.config/matplotlib目录下面;
4. 另外折腾半天,也没有网上提到的fontList.cache文件生成,都想重新从git库检出matplotlib进行手动安装,但下载太慢放弃了。
5. 不同ubuntu下可用的中文字体不一样,网上很多说什么将matplotlibrc的serif字体中加入YaHei等等,根本没有考虑机器的使用环境。。。

因此,安装步骤如下:
1. 确认你ubuntu系统环境下拥有的中文字体文件
fc-list :lang=zh
命令输出如下:

/usr/share/fonts/truetype/arphic/uming.ttc: AR PL UMing TW MBE:style=Light
/usr/share/fonts/truetype/arphic/ukai.ttc: AR PL UKai CN:style=Book
/usr/share/fonts/truetype/arphic/ukai.ttc: AR PL UKai HK:style=Book
/usr/share/fonts/truetype/arphic/ukai.ttc: AR PL UKai TW:style=Book
/usr/share/fonts/truetype/wqy/wqy-microhei.ttc: WenQuanYi Micro Hei,文泉驛微米黑,文泉驿微米黑:style=Regular
/usr/share/fonts/truetype/droid/DroidSansFallbackFull.ttf: Droid Sans Fallback:style=Regular
/usr/share/fonts/truetype/arphic/ukai.ttc: AR PL UKai TW MBE:style=Book
/usr/share/fonts/truetype/arphic/uming.ttc: AR PL UMing TW:style=Light
/usr/share/fonts/truetype/arphic/uming.ttc: AR PL UMing CN:style=Light
/usr/share/fonts/truetype/arphic/uming.ttc: AR PL UMing HK:style=Light
/usr/share/fonts/truetype/wqy/wqy-microhei.ttc: WenQuanYi Micro Hei Mono,文泉驛等寬微米黑,文泉驿等宽微米黑:style=Regular

我从中选择了Droid Sans Fallback字体
2. 在python脚本中手动加载中文字体

import matplotlib.pyplot as plt
import matplotlib as mpl
zhfont = mpl.font_manager.FontProperties(fname='/usr/share/fonts/truetype/droid/DroidSansFallbackFull.ttf')
plt.plot([1, 2, 3])
plt.xlabel(u'x轴标签', fontproperties=zhfont)
plt.show()

通过以上方法,应该就能正确显示字体了。