说明:
- 其他字体缺失的报错可使用类似方法解决。
- 首先需要安装
python
包matplotlib
,若没安装可执行conda install -c conda-forge matplotlib -y
安装。 - 这里使用
conda
安装,对于python
包,建议使用者学习用conda
安装,conda
安装不了再用pip
安装。 - 若有需求,后续可再出一篇
python
使用及包管理的文章,教大家如何良好安装python
包及环境管理。
-
首先查看系统是否存在需要使用的字体:
import matplotlib.font_manager ttf_name = "SimHei" font_list = matplotlib.font_manager.findSystemFonts(fontpaths=None, fontext='ttf') for font in font_list: if f'{ttf_name}.ttf' in str(font).lower(): print(font)
-
如果系统有相应字体,可直接拷贝,否则下载simhei字体文件,将字体文件
SimHei.ttf
拷贝到$(dirname "$(python -c "import matplotlib;print(matplotlib.matplotlib_fname())")")/fonts/ttf/
。 -
修改
matplotlibrc
# cd到matplotlibrc的路径 cd $(dirname "$(python -c "import matplotlib; print(matplotlib.matplotlib_fname())")") # 修改 sed -i '/^#font.family/c\font.family: sans-serif' matplotlibrc sed -i 's/^#font.sans-serif: /font.sans-serif: SimHei, /' matplotlibrc sed -i 's/#axes.unicode_minus: True/axes.unicode_minus: False/' matplotlibrc
-
清除缓存
rm -rf ~/.cache/matplotlib
-
测试
import matplotlib.pyplot as plt plt.plot([1, 2, 3], [100, 500, 300]) plt.title('matplotlib中文字体测试', fontsize=25) plt.xlabel('x轴', fontsize=15) plt.ylabel('y轴', fontsize=15) plt.savefig('test.png')
linux
系统可使用eog
或display
在命令行查看图片,如eog test.png
,可看到图片中中文正常显示,不再是小方块。