Ubuntu18中,使用Python的matplotlib库设置simhei.ttf中文字体并显示
- 首先,下载中文字体simhei.ttf
- 其次,需要知道当前使用的matplotlib库的环境配置
即使用语句:
import matplotlib
print(matplotlib.matplotlib_fname())可得:
可以推测出matplotlib的字体文件就在mpl-data/文件夹下的fonts/ttf/文件夹下。即路径:/home/peter/anaconda3/envs/py3torch1/lib/python3.6/site-packages/matplotlib/mpl-data/fonts/ttf - 然后将字体文件simhei.ttf移动到ttf/文件夹下。
- 然后使用代码:
from matplotlib.font_manager import _rebuild
_rebuild()
来重构字体库(执行了一次即可)。 - 最后,在Python程序中直接使用语句:
plt.rcParams[‘font.sans-serif’]=[‘simhei’]
即可设置中文字体并在使用matplotlib画图时显示中文字体。