matplotlib顯示不了中文,主要問題在於沒有指定中文字體。
解決方法有有很多種,有修改matplotlib配置文件,還有替換matplotlib的mpl-data
文件夾下字體文件的,這些方法不夠靈活,以下兩種方法相對靈活一些。
方法一
#-*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams['font.sans-serif'] = ['FangSong_GB2312']
#指定的字體爲系統自帶的字體,這種方法關鍵在於要知道操作系統自帶的字體的名稱
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_title(u'試試看')
plt.show()
方法二
#-*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import matplotlib
fig = plt.figure()
ax = fig.add_subplot(111)
font_path = matplotlib.font_manager.FontProperties(fname='msyh.ttf')
#指定字體爲同目錄下的msyh.ttf即微軟雅黑
ax.set_title(u'試試看',fontproperties=font_path)
plt.show()