如果本来就没有中文字体,必须先安装并配置字体,保证有中文字体ttf的文件
配置:修改matplotlibrc配置字体
1. 首先定位matplotlib的字体库路径(我使用python进行定位)
import matplotlib
matplotlib.matplotlib_fname()
2. 将中文字体文件**.ttf,拷贝到该目录的fonts/ttf下
3. 删除 matplotlib 缓存
cd ~/.cache/matplotlib
rm * -r
4. 修改matplotlibrc文件:修改font.sans-serif 加入中文字体
font.sans-serif : Microsoft YaHei, DejaVu Sans, Bitstream Vera Sans, Computer Modern Sans Serif, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif, ***(刚加的字体名字)
5. 重启程序或在 jupyter中restart the kernel
应用一:用plt.rcParams设置
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['Microsoft YaHei']
plt.xlabel('测试')
plt.show()
应用二:用FontProperties,并指定字体文件
from matplotlib.font_manager import FontProperties
import matplotlib.pyplot as plt
font = FontProperties(fname='/mnt/share/code/font/SimHei.ttf', size=20)
plt.title('测试', fontproperties=font)