centos7 matplotlib应用之霍兰德人格分析中中文乱码问题

1.问题分析:在应用matplotlib绘制图表时出现的中文乱码问题在大部分情况下是由于其字体库中没有相应的中文字体支持(图中出现的空格就是乱码现象),故解决方法-导入中文字体
在这里插入图片描述
2.预先了解系统当前状态(是否已存在中文字体包、当前使用中的字体)
查询已存在的中文字体包
from matplotlib.font_manager import FontManager
import subprocess
fm = FontManager()
mat_fonts = set(f.name for f in fm.ttflist)
print(mat_fonts)
output = subprocess.check_output(‘fc-list :lang=zh -f “%{family}\n”’, shell=True)
print(’’ * 10, ‘系统可用的中文字体’, '’ * 10)
print(output)
zh_fonts = set(f.split(’,’, 1)[0] for f in output.decode().split(’\n’))
available = mat_fonts & zh_fonts
print(’’ * 10, ‘可用的字体’, '’ * 10)
for f in available:
print(f)
在这里插入图片描述
如果没有查找到任何的中文字体包,则需要从系统外导入或下载

查询正在使用的字体
from matplotlib.font_manager import findfont, FontProperties
print(findfont(FontProperties(family=FontProperties().get_family())))
在这里插入图片描述
此处表明当前字体为STXIHEI,还有字体存放路径(稍后可向这个路径存放字体包)
3.解决问题
(1)若系统中不含有中文字体包,则考虑从windows系统中复制(可用XShell工具),其存储路径一般在C:\Windows\Fonts,不过要注意字体包的格式问题,TTC格式好像不是很兼容,最好使用TTF格式,并将其复制到上面找出的目录中
(2)复制好之后,在上述路径中的mpl-data处进入终端,开启root权限,使用 vi matplotlibrc命令编辑matplotlibrc文档

在这里插入图片描述
在这里插入图片描述

将 font.family 及 font.sans-serif 前面的#去掉,然后在font.sans-serif:后面增加你所导入的字体名。保存退出
然后执行
from matplotlib.font_manager import _rebuild
_rebuild()
重新设定
搞定!
在这里插入图片描述

发布了1 篇原创文章 · 获赞 0 · 访问量 22

猜你喜欢

转载自blog.csdn.net/qq_42345349/article/details/104578498
今日推荐