問題:
我在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代碼中手動加載中文字體:
示例代碼如下:
1 #coding:utf-8 2 from matplotlib.font_manager import FontProperties 3 import matplotlib.pyplot as plt 4 font = FontProperties(fname='/usr/share/fonts/truetype/droid/DroidSansFallbackFull.ttf', size=14) 5 plt.figure() 6 plt.plot([1, 2, 3]) 7 plt.xlabel(u"電壓差(V)", fontproperties=font) 8 plt.ylabel(u"介質損耗角差(度)", fontproperties=font) 9 plt.title(u"介質損耗角和荷電狀態SOC關系圖",fontproperties=font) 10 fig_name = '訓練性能' + '.pdf' 11 plt.savefig(fig_name) 12 plt.show()
參考資料:
Linux下python matplotlib.pyplot在圖像上顯示中文的問題