在使用python matplotlib 画图时,由于matplotlib 默认是使用DejaVu Sans这种字体,不支持中文,所以我们在使用matplotlib画图包含中文内容要显示时就会变成方框,并输出警告
那么我们该怎么设置显示中文呢?
下面我来分享一下我的经验:
1.查看matplotlib 字体库中的字体
from matplotlib import pyplot as pltimport matplotlibprint(matplotlib.font_manager.fontManager.ttflist) # 输出所有的字体名
输出效果:
列表元素为:
<Font 'DejaVu Serif' (DejaVuSerif-BoldItalic.ttf) italic normal 700 normal>
类型为 <class 'matplotlib.font_manager.FontEntry'>
这里包含了 字体名、字体文件名等。
通过dir(matplotlib.font_manager.fontManager.ttflist[0])可以查看FontEntry对象的所有用法:
['__class__','__delattr__','__dict__','__dir__','__doc__','__eq__','__format__','__ge__','__getattribute__','__gt__','__hash__','__init__','__init_subclass__','__le__','__lt__','__module__','__ne__','__new__','__reduce__','__reduce_ex__','__repr__','__setattr__','__sizeof__','__str__','__subclasshook__','__weakref__','fname', # 文件路径名 'name', # 字体名'size', 'stretch','style','variant','weight']
我们可以通过fname属性查看字体的路径、文件名:
matplotlib.font_manager.fontManager.ttflist[0].fname 得到
'c:\\users\\administrator\\appdata\\local\\programs\\python\\python38\\lib\\site-packages\\matplotlib\\mpl-data\\fonts\\ttf\\DejaVuSerif-BoldItalic.ttf'
我们可以通过name属性查看字体名:
matplotlib.font_manager.fontManager.ttflist[0].name 得到'DejaVu Serif',有了这个字体名,我们就可以设置我们想要的字体了,用for循环遍历matplotlib.font_manager.fontManager.ttflist得到所有字体名了。
font_list = matplotlib.font_manager.fontManager.ttflistfont_set = set() # 字体路径与字体名匹配的集合fname_set = set() # 字体路径的集合name_set = set() # 字体名的集合for font in font_list:font_set.add((font.fname,font.name))fname_set.add(font.fname)name_set.add(font.name)
上面定义了三个集合
font_set = set() # 字体路径与字体名匹配的集合,用来找到对应的字体。
fname_set = set() # 字体路径的集合,我们看看matplotlib的字体都来源于哪。
name_set = set() # 字体名的集合,设置我们想要的字体就从这里拿了。
接下来我们输出看看:
我们先把路径文件夹提取出来,看看是哪几个文件夹:
import osfload_set = set()for i in fname_set:fload_set.add(os.path.split(i)[0]) # 用os.path.split提取文件路径中的路径
输出:
这里可以看到,一共有四个路径,我的电脑是win10系统,
'C:\\ProgramData\\kingsoft\\office6\\mtfont' 是wps的字体路径
'C:\\Windows\\Fonts'是windows系统的字体路径
'D:\\SolidWorks\\SOLIDWORKS\\HoopsPublish\\resource\\Font' 是3d绘图软件SOLIDWORKS的字体路径
'c:\\users\\administrator\\appdata\\local\\programs\\python\\python38\\lib\\site-packages\\matplotlib\\mpl-data\\fonts\\ttf' 是matplotlib自带的字体路径
所以matplotlib获取到的字体不仅有它自带的字体,还吸取了我们安装的很多字体。
快速输出几种常用中文字体:
from matplotlib import pyplot as pltimport matplotlibch_set = set()for i in matplotlib.font_manager.fontManager.ttflist: # matplotlib所有的字体名列表if 'Kai' in str(i): # 包含'Kai'的字体(楷体类)ch_set.add(i.name)elif 'Song' in str(i): # 包含'Song'的字体(宋体类)ch_set.add(i.name) elif 'Hei' in str(i): # 包含'Hei'的字体(黑体类)ch_set.add(i.name)ch_set # 输出
输出:
{'Adobe Heiti Std','Adobe Song Std','FZCuHeiSongS-B-GB','FangSong','HYSWLongFangSong','KaiTi','Microsoft JhengHei','Microsoft YaHei','SimHei'}
2.设置我们想要的中文字体
比如我们想用【汉仪长仿宋体】,我们得先知道它的字体名叫什么,才能应用于matplotlib。
桌面右键点【个性化】→【字体】
【可用字体】下方输入框输入框输入【汉仪】关键字搜索字体,然后点击下方搜索到的字体
弹出对应字体信息界面可以看到字体的路径
接下来我们输出指定字体的字体名:
for i in font_set: # font_set看上面代码if i[0] == 'C:\\Windows\\Fonts\\hyswlongfangsong.ttf': # 匹配font_set里的路径print(i[1])break
输出结果:
字体名就是【HYSWLongFangSong】了
这里看到的文件名不一定就是字体名哦,比如【方正粗黑宋简体.ttf】是【FZCuHeiSongS-B-GB】
设置对应字体 的代码就是 plt.rcParams['font.family'] = ['HYSWLongFangSong']
也要注意字体只支持特定的语种我们要显示中文就必须选择一种支持中文的字体
3.看一下效果:
import pandas as pdimport matplotlib.pyplot as pltplt.rcParams['font.family'] = ['HYSWLongFangSong']# 创建三位学生成绩数据students_grade = pd.DataFrame({'张三': [79, 83, 82, 90, 78, 75],'李四': [93, 91, 93, 95, 95, 97],'王五': [80, 81, 85, 81, 86, 92]})# 定义画布大小plt.figure(figsize=(16, 8))# 设置标题plt.title('月考分数对比', fontsize = 32, color = 'blue')# 设置柱体颜色colors = ['r','g','b']# 定义X轴标签列表month = ['2月', '3月', '4月', '5月', '6月', '7月']# 定义学生姓名列表name_list = students_grade.columns# 循环创建三位学生成绩for i in range(3):# 画柱状图(X轴位置、柱子高度、柱体颜色、柱子宽度、柱体透明度)plt.bar(students_grade.index + 0.2*(i-1), students_grade[name_list[i]].values,color = colors[i] , width = 0.2, alpha = 0.6)# 设置刻度名称plt.xticks(students_grade.index, month, fontsize=20) # 位置、值、字体大小plt.yticks(fontsize=20)# 设置坐标轴标签plt.xlabel('月份', fontsize=24)# 标签、字体大小、旋转角度(默认90°)plt.ylabel('分 \n数 ', fontsize=24, rotation=0) # 设置数据标签for a,b in zip(students_grade.index, students_grade[name_list[i]].values):# X轴位置、Y轴位置、值、对齐方式、字体大小plt.text(a + 0.2*(i-1), b, b, ha='center', fontsize = 24) # 设置图例plt.legend(name_list)
4.安装新字体
比如我的windows系统,没有【Source Han Sans CN】、【华文彩云】等这种字体,我在字客网下载下来后解压出字体,拖动到C:\Windows\Fonts目录下安装上了。但是这时,matplotlib字体中仍然找不到这个字体,这时需要我们清理下matplotlib的字体缓存。
大家可以使用下面的代码
import matplotlib as pltplt.get_cachedir()
输出matplotlib字体缓存的目录:C:\Users\Administrator\.matplotlib 我这边缓存就在这个目录了。
把这个目录删掉,退出当前正在使用的编辑器如 jupyter ,在下次启动编辑器导入matplotlib库就会再次生成这个缓存文件夹,再次设置字体就会自动生成这个字体缓存文件了。
来看看新字体华文彩云【STCaiyun】的效果