问题:
我在ubuntu14.04下用python中的matplotlib模块内的pyplot输出图片不能显示中文,怎么解决呢?
解决:
1.指定默认编码为UTF-8:
在python代码开头加入如下代码
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
2.确认你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字体。
3.在python代码中手动加载中文字体:
示例代码如下:
#coding:utf-
from matplotlib.font_manager import FontProperties
import matplotlib.pyplot as plt
font = FontProperties(fname='/usr/share/fonts/truetype/droid/DroidSansFallbackFull.ttf', size=)
plt.figure()
plt.plot([, , ])
plt.xlabel(u"电压差(V)", fontproperties=font)
plt.ylabel(u"介质损耗角差(度)", fontproperties=font)
plt.title(u"介质损耗角和荷电状态SOC关系图",fontproperties=font)
fig_name = '训练性能' + '.pdf'
plt.savefig(fig_name)
plt.show()
参考资料: