Matplotlib支持中文: Mac

Matplotlib是支持Unicode的,所以支持中文的一种简单的方法是使用其font_manager函数指定中文字体(其他语言的字体也是同样的道理),然后用u'中文'这样的形式将中文转换为Unicode即可。

查看系统的中文字体

终端中使用命令 fc-list :lang=zh即可查看系统内所有中文字体及字体文件的路径,比如:

/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,Обычный,常规体
/Library/Fonts/Songti.ttc: Songti TC,宋體\-繁,宋体\-繁:style=Regular,標準體,常规体
/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,Обычный,常规体
/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'正弦函数',fontproperties=myfont)

注意:如果使用.ttc文件指定字体文件,保存pdf文件的时候出现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'正弦函数',fontproperties= zhfont)
plt.plot(x,y)

plt.show()
matplotlib使用中文范例

你可能感兴趣的:(Matplotlib支持中文: Mac)