问题描述
使用matplotlib画图时,因为缺少字体,出现warning,图像上label上的中文显示时空白小方块。因为matplotlib默认没有中文,可以调用中文字体,但是会出现如下图所示的warning:
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
1.png
解决方法
Step 1. 在终端进入python3环境,查看matplotlib字体路径:
import matplotlib
print(matplotlib.matplotlib_fname())
2.png
找到自己的matplotlib字体文件路径:
比如/Users/dan/miniforge3/envs/py38/lib/python3.8/site-packages/matplotlib/mpl-data/matplotlibrc
Step 2. 下载SimHei.ttf字体:
国内SimHei
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
或者复制改文件:
cp ~/Downloads/SimHei.ttf ~/miniforge3/envs/py38/lib/python3.8/site-packages/matplotlib/mpl-data/fonts/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进行修改:
3.png
通过vi定位几个关键点来修改:
使用查找功能尤为重要。方法如下:
1、命令模式下输入“/字符串”,例如“/Section 3”。
2、如果查找下一个,按“n”即可。
#去掉前面的#
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
编辑完按Esc退出编辑模式此时输入::wq
:wq
保存后退出
:wq!
强制保存后退出
:w
保存但不退出
:w!
若文件属性为只读时,强制写入该文档
:q
不保存并退出
:q!
不保存并强制退出
Step 6. 重启,测试
import matplotlib.pyplot as plt
x = list(range(5))
y = list(range(1,10,2))
plt.plot(x,y)
plt.xlabel('x轴数据')
plt.ylabel('y轴数据')
plt.show()
4.png
不需要plt.rcParams['font.sans-serif'] = ['SimHei']
就可以自动显示中文,至此中文显示的问题已经解决。
参考:link 1