Mac系统下matplotlib中SimHei中文字体缺失报错的解决办法

问题描述

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei'] 
plt.rcParams['axes.unicode_minus']=False

使用matplotlib画图时,因为缺少字体,、图像上label上的中文显示时空白小方块。因为matplotlib默认没有中文。

解决方法:

Step 1. 在终端进入python3环境,查看matplotlib字体路径:

import matplotlib    
print(matplotlib.matplotlib_fname())

找到自己的matplotlib字体文件路径:

/Users/zhangzhang/miniforge3/envs/py38_pytorch/lib/python3.8/site-packages/matplotlib/mpl-data/fonts/ttf

(这里的路径与上面找出来的路径不一致,需要手动删除matplotlibrc,并添加fonts/ttf)

Step 2. 下载SimHei.ttf字体:

国内SimHei:https://www.duote.com/soft/915316.html

下载后,解压,并命名为SimHei.ttf

Step 3. 将下载好的SimHei.ttf字体移动到第一步查询到的字体目录./fonts/ttf/下:

mv 下载路径 目标路径

mv /Users/zhangzhang/Downloads/SimHei.ttf /Users/zhangzhang/miniforge3/envs/py38_pytorch/lib/python3.8/site-packages/matplotlib/mpl-data/fonts/ttf

(也可以手动找出路径,手动移)

Step 4. 打开终端,进入python环境,清理matplotlib缓冲目录:

import matplotlib
print(matplotlib.get_cachedir())

获取缓冲目录地址:/Users/zhangzhang/.matplotlib

终端输入exit()退出python环境,再删除上面找到的缓冲文件:

rm -rf /Users/dan/.matplotlib

Step 5. 修改原始文件:

打开第一步找到的路径:/Users/zhangzhang/miniforge3/envs/py38_pytorch/lib/python3.8/site-packages/matplotlib/mpl-data/matplotlibrc进行修改:

通过/定位(例如/font.sans-serif来定位),来修改下面三个地方:

#去掉前面的#
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

Step 6. 重启,测试。 (此时默认显示中文字体)

import matplotlib.pyplot as plt
plt.title('显示中文')
x = np.arange(7)
y = x
plt.plot(x, y, 'r-')
plt.xlabel('x轴')
plt.ylabel('y轴')
plt.show()

不需要plt.rcParams['font.sans-serif'] = ['SimHei']就可以自动显示中文,至此中文显示的问题已经解决。

猜你喜欢

转载自blog.csdn.net/ProceduralMan/article/details/128682590
今日推荐