中文字体不能显示,是因为matplotlib会默认使用自己的一套字体库,这套字体库里面并没有中文字体。因此如果需要渲染中文字体的话,要么自己把需要的中文字体文件添加到matplotlib的字体目录中,或者把字体文件路径添加到matplotlib的字体搜索路径中。
第一种方式
import matplotlib
import os
print(matplotlib.matplotlib_fname()) # matplotlib配置文件目录
# 字体文件目录
print(os.path.join(os.path.dirname(matplotlib.matplotlib_fname()), 'fonts', 'ttf'))
把你需要的字体文件(ttf)复制到上面显示的.fonts\ttf文件夹中。
之后重新编译字体缓存文件。
import matplotlib.font_manager
matplotlib.font_manager._rebuild()
使用方法
matplotlib.rcParams['font.family'] = ['Heiti TC'] # 这里需要更换成你添加字体的字体名
第二种方式
import matplotlib.font_manager as mfm
import matplotlib.pyplot as plt
font_path = "/usr/share/fonts/custom/simhei.ttf"
prop = mfm.FontProperties(fname=font_path)
plt.text(0.5, 0.5, s=u'测试', fontproperties=prop)
plt.show()
使以上两种方式可以在figure中正确显示中文,但仍然不能保存为eps格式,可以先保存为pdf格式,之后再使用AI等矢量绘图软件打开即可。不过所有的文字都会被自动转成路径。