Matplotlib是支持Unicode的旭贬,所以支持中文的一種簡單的方法是使用其font_manager
函數(shù)指定中文字體(其他語言的字體也是同樣的道理)赊抖,然后用u'中文'
這樣的形式將中文轉(zhuǎn)換為Unicode即可橄浓。
查看系統(tǒng)的中文字體
終端中使用命令 fc-list :lang=zh
即可查看系統(tǒng)內(nèi)所有中文字體及字體文件的路徑艾疟,比如:
/System/Library/Fonts/PingFang.ttc: .PingFang HK,.蘋方\-港,.蘋方\-港:style=Thin,纖細體,纖細體
/System/Library/Fonts/PingFang.ttc: .PingFang SC,.蘋方\-簡,.蘋方\-簡:style=Thin,纖細體,纖細體
/Library/Fonts/Songti.ttc: STSong:style=Regular,標準體,Ordin?r,Normal,Normaali,Regolare,レギュラー,???,Regulier,Обычный,常規(guī)體
/Library/Fonts/Songti.ttc: Songti TC,宋體\-繁,宋體\-繁:style=Regular,標準體,常規(guī)體
/System/Library/Fonts/Hiragino Sans GB.ttc: Hiragino Sans GB,冬青黑體簡體中文,冬青黑體簡體中文,冬青黑體簡體中文 W6,Hiragino Sans GB W6,冬青黑體簡體中文 W6:style=W6,Bold
/Library/Fonts/NISC18030.ttf: GB18030 Bitmap:style=Regular,標準體,Ordin?r,Normal,Normaali,Regolare,レギュラー,???,Regulier,Обычный,常規(guī)體
/Library/Fonts/Songti.ttc: Songti TC,宋體\-繁,宋體\-繁:style=Light,細體,細體
/Users/zguo/Library/Fonts/STSongti-SC-Black.ttf: Songti SC,宋體\-簡,宋體\-簡:style=Black,黑體,黑體
/Library/Fonts/Songti.ttc: Songti SC,宋體\-簡,宋體\-簡:style=Light,細體,細體
/Users/zguo/Library/Fonts/SourceHanSansCN-Regular.otf: Source Han Sans CN,思源黑體 CN,Source Han Sans CN Regular,思源黑體 CN Regular:style=Regular
/Users/zguo/Library/Fonts/STSongti-TC-Bold.ttf: Songti TC,宋體\-繁,宋體\-繁:style=Bold,粗體,粗體
/System/Library/Fonts/PingFang.ttc: PingFang SC,蘋方\-簡,蘋方\-簡:style=Semibold,中粗體,中粗體
/System/Library/Fonts/PingFang.ttc: PingFang HK,蘋方\-港,蘋方\-港:style=Semibold,中粗體,中粗體
/System/Library/Fonts/Hiragino Sans GB.ttc: Hiragino Sans GB,冬青黑體簡體中文,冬青黑體簡體中文,冬青黑體簡體中文 W3,Hiragino Sans GB W3,冬青黑體簡體中文 W3:style=W3,Regular
/System/Library/Fonts/LastResort.otf: .LastResort:style=Regular
/System/Library/Fonts/PingFang.ttc: PingFang TC,蘋方\-繁,蘋方\-繁:style=Semibold,中粗體,中粗體
matplotlib中使用中文
要點1:定義自己所需的中文字體 zhfont=mpl.font_manager.FontProperties(fname="/Library/Fonts/Songti.ttc")
要點2:plt.title(u'正弦函數(shù)',fontproperties=myfont)
注意:如果使用
.ttc
文件指定字體文件缸榛,保存pdf文件的時候出現(xiàn)TrueType font is missing table
錯誤劳淆。則嘗試使用.ttf
文件(同樣使用fc-list :lang=zh | grep ".ttf"
命令查找字體文件目錄)代替可以解決此問題
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
zhfont=mpl.font_manager.FontProperties(fname="/Library/Fonts/Songti.ttc")
# mpl.rcParams['axes.unicode_minus'] = False
x=np.linspace(-np.pi,np.pi,100)
y=np.sin(x)
plt.title(u'正弦函數(shù)',fontproperties= zhfont)
plt.plot(x,y)
plt.show()
matplotlib使用中文范例