解决办法:
Step 1. 在终端进入python3环境,查看matplotlib字体路径:
import matplotlib
print(matplotlib.matplotlib_fname())
找到自己的matplotlib字体文件路径:
比如/Users/dan/miniforge3/envs/py38/lib/python3.8/site-packages/matplotlib/mpl-data/matplotlibrc
Step 2. 下载SimHei.ttf字体:
Step 3. 将下载好的SimHei.ttf字体移动到第一步查询到的字体目录./fonts/ttf/下:
mv ~/Downloads/SimHei.ttf ~/miniforge3/envs/py38/lib/python3.8/site-packages/matplotlib/mpl-data/fonts/ttf/SimHei.ttf
注意字体文件名称一定是:SimHei.ttf
Step 4. 打开终端,进入python环境,清理matplotlib缓冲目录:
import matplotlib
print(matplotlib.get_cachedir())
获取缓冲目录地址:/Users/dan/.matplotlib
终端输入exit()退出python环境,再删除上面找到的缓冲文件:
rm -rf /Users/dan/.matplotlib
Step 5. 修改原始文件:
打开第一步找到的字体路径:/Users/dan/miniforge3/envs/py38/lib/python3.8/site-packages/matplotlib/mpl-data/matplotlibrc进行修改:
通过vi定位几个关键点来修改:
vi /Users/dan/miniforge3/envs/py38/lib/python3.8/site-packages/matplotlib/mpl-data/matplotlibrc
通过:/内容 查找指定内容 如:/font.family, :/font.sans-serif,😕 axes.unicode_minus.
#去掉前面的#
font.family: sans-serif
#去掉前面的#,手动加SimHei
font.sans-serif: SimHei, DejaVu Sans, Bitstream Vera Sans, Computer Modern Sans Serif, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif
#去掉前面的#,把True改为False
axes.unicode_minus: False # use Unicode for the minus symbol rather than hyphen. See
# https://en.wikipedia.org/wiki/Plus_and_minus_signs#Character_codes