Generic family ‘sans-serif’ not found because none of the following families were found: SimHei
运行
import matplotlib.pyplot as plt
plt.rcParams[“font.sans-serif”] = [“SimHei”]
报错
-
在python环境中输入以下代码,查看字体路径:
import matplotlib
matplotlib.matplotlib_fname()
结果如下:venv/lib/python3.8/site-packages/matplotlib/mpl-data/matplotlibrc -
下载所需要字体SimHei
方式一:官网下载
方式二:
将下载好的文件放到/Users/xxx/PycharmProjects/learnPython/venv/lib/python3.8/site-packages/matplotlib/mpl-data/fonts/ttf/路径下
3. 删除matplotlib的字体缓存
首先,查看matplotlib的字体缓存路径:
import matplotlib
matplotlib.get_cachedir()
结果为
‘/Users/chenbinhao/.matplotlib’
删除该路径:rm -rf /Users/xxx/.matplotlib
4. 修改matplotlibrc文件
修改如下路径中的matplotlibrc文件:
去掉前面的#号
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
5. 重新运行脚本即可正常显示中文