Generic family ‘sans-serif‘ not found because none of the following families

2023-05-16

1背景

python使用matplot绘图标注中文时,出现乱码,部分python代码如下:

    # 解决中文显示问题
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.rcParams['axes.unicode_minus'] = False

2原因

因为上述代码中使用了SimHei字体,但是在当前python的环境中没有该字体数据

3解决

首先要明确当前执行python的用户是root还是其他普通用户,针对具体用户的python环境进行处理。

大概思路:获取字体文件->拷贝至python环境->修改python配置文件

3.1获取字体文件

可以从网上下载也可以从windos中拷贝(通常在这个目录:C:\Windows\Fonts)。

注意:从windos系统获取有个小技巧,需将整个C:\Windows\Fonts中文件都拷贝到桌面新建的目录中,才能看到simhei.ttf文件

3.2拷贝至python环境

检索python环境的字体目录:

[root@localhost ~]# find / -path "*matplotlib/mpl-data/fonts/ttf" 
/home/user_test/.local/lib/python3.9/site-packages/matplotlib/mpl-data/fonts/ttf
/usr/local/python3/lib/python3.9/site-packages/matplotlib/mpl-data/fonts/ttf

 由于我执行python用的是user_test用户,因此,只需要将simhei.ttf拷贝到【/home/user_test/.local/lib/python3.9/site-packages/matplotlib/mpl-data/fonts/ttf】目录下即可。

3.3修改python配置文件

检索python配置文件:

[root@localhost ~]# find / -path "*matplotlibrc"
/home/user_test/.local/lib/python3.9/site-packages/matplotlib/mpl-data/matplotlibrc
/usr/local/python3/lib/python3.9/site-packages/matplotlib/mpl-data/matplotlibrc

同样的,由于我执行python用的是user_test用户,只需修改【/home/user_test/.local/lib/python3.9/site-packages/matplotlib/mpl-data/matplotlibrc】

[root@localhost ~] vi /home/user_test/.local/lib/python3.9/site-packages/matplotlib/mpl-data/matplotlibrc
font.family         : sans-serif
font.sans-serif     : SimHei, Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif,WenQuanYi Zen Hei Mono
#True改为False,处理'-'符号显示为方块的问题
axes.unicode_minus  : False 

确保有如上三行(不要有重复项)

搞定!!!!!!!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Generic family ‘sans-serif‘ not found because none of the following families 的相关文章

随机推荐