導言
Matplotlib是一款強大的可視化工具,然而,其默認不支持中文的顯示,其實,只要在顯示的時候,指定好特定的中文字體,即可正常顯示中文。
在下面的文件中,show_available_font 函數打印出可用的字體,然後根據返回的結果,在/usr/share/fonts 路徑下進行搜索對應的庫文件。其次,myfont = matplotlib.font_manager.FontProperties(fname=’/usr/share/fonts/truetype/droid/DroidSansFallbackFull.ttf’) 用於加載該字體,plt.title(u’這裏寫的是中文’,fontproperties=myfont) 用於指定顯示的字體。
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 16 15:54:17 2016
Linux 下,matplotlib顯示中文。
@author: [email protected]
"""
from pylab import matplotlib,mpl
from matplotlib.font_manager import FontManager
import subprocess
import matplotlib.pylab as plt
import numpy as np
def show_available_font():
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)
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
def test():
myfont = matplotlib.font_manager.FontProperties(fname='/usr/share/fonts/truetype/droid/DroidSansFallbackFull.ttf')
mpl.rcParams['axes.unicode_minus'] = False
pi = 3.1415926
t = np.arange(-5*pi, 5*pi, 0.01)
y = np.sin(t)/t
plt.plot(t, y)
plt.title(u'這裏寫的是中文',fontproperties=myfont) #指定字體
plt.xlabel(u'X座標',fontproperties=myfont)
plt.ylabel(u'Y座標',fontproperties=myfont)
plt.show()
if __name__ == "__main__":
show_available_font()
test()
即可正常顯示中文字體。