問題描述
在使用matplotlib(或seaborn)時,中文無法正常顯示,顯示結果爲一個方框
環境:Windows+Anaconda
解決方法
方法一:設置plt的參數
plt.rcParams['font.sans-serif']=['SimHei'] #用來正常顯示中文標籤
plt.rcParams['axes.unicode_minus']=False #用來正常顯示負號
另外:如果用了seaborn這樣的基於matplotlib的庫的話,需要額外設置:
sns.set(font='SimHei')
方法二:直接指定字體路徑
import matplotlib.font_manager as fm
fonts = fm.FontProperties(fname=r'C:\Windows\Fonts\SimHei.ttf') # 設置字體
plt.xlabel(u'橫軸',fontproperties=fonts)
plt.ylabel(u'縱軸',fontproperties=fonts)
方法三:手動修改matolotlib配置文件matplotlibrc
matplotlibrc的位置可用以下方式獲得
import matplotlib
matplotlib.matplotlib_fname() #將會獲得matplotlib包所在文件夾
1.打開matplotlibrc,分別找到以下項目,去掉前面的#註釋
#font.serif : DejaVu Serif, Bitstream Vera Serif, Computer Modern Roman, New Century Schoolbook, Century Schoolbook L, Utopia, ITC Bookman, Bookman, Nimbus Roman No9 L, Times New Roman, Times, Palatino, Charter, serif
#font.sans-serif : SimHei, DejaVu Sans, Bitstream Vera Sans, Computer Modern Sans Serif, Lucida Grande, Verdana, Geneva, Lucid, Arial,
#axes.unicode_minus : False ## use unicode for the minus symbol 用來正常顯示負號
2.找到需要的中文字體,複製到fonts中的ttf目錄下,位置在剛剛的matplotlibrc同一級文件夾中的fonts\ttf
3.將我們的字體文件的註冊名字(如SimHei)加到配置文件項serif和sans-serif後面的第一個
#font.serif : SimHei, Bitstream Vera Serif, New Century Schoolbook, Century Schoolbook L, Utopia, ITC Bookman, Bookman, Nimbus Roman No9 L, Times New Roman, Times, Palatino, Charter, serif
#font.sans-serif : SimHei, DejaVu Sans, Bitstream Vera Sans, Computer Modern Sans Serif, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif
4.到了這步應該就解決了,如果還是不能正常顯示,可以在python中重新加載一下字體
from matplotlib.font_manager import _rebuild
_rebuild() #重新加載一下