在Mac下,使用matplotlib.pyplot画图出现中文乱码
同时控制台也会报下列错误
1 2 3 4 5 6 | /Users/chentingxuan/opt/anaconda3/lib/python3.7/site-packages/matplotlib/backends/backend_agg.py:180: RuntimeWarning: Glyph 21475 missing from current font. font.set_text(s, 0, flags=flags) /Users/chentingxuan/opt/anaconda3/lib/python3.7/site-packages/matplotlib/backends/backend_agg.py:180: RuntimeWarning: Glyph 23736 missing from current font. font.set_text(s, 0, flags=flags) /Users/chentingxuan/opt/anaconda3/lib/python3.7/site-packages/matplotlib/backends/backend_agg.py:180: RuntimeWarning: Glyph 19978 missing from current font. font.set_text(s, 0, flags=flags) |
错误显示为,我们没有设置对应的字体,于是我们尝试按照网上的方法,添加两行代码,即
1 2 | plt.rcParams['font.sans-serif'] = ['SimHei'] #设置字体,设置了字体后,负号会变成乱码 plt.rcParams['axes.unicode_minus'] = False #让负号的乱码正常显示 |
但是同样也会出现乱码问题,并且控制台也报找不到字体的错误
1 | findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans. |
于是,我们就需要从官网上去将对应的字体下载,并配置。
1. 下载字体
官网地址:SimHei字体
2. 复制字体
将下载的字体“SimHei.ttf"复制到"/Users/XXX/opt/anaconda3/lib/python3.7/site-packages/matplotlib/mpl-data/fonts/ttf"
3. 修改matplotlibrc文件
matplotlibrc文件在"/Users/XXX/opt/anaconda3/lib/python3.7/site-packages/matplotlib/mpl-data",直接使用Mac自带文本编辑器打开
在文件中找到"#font,family"
修改内容如下:
1 2 3 4 5 6 | # 去掉前面的# font.family : sans-serif # 去掉前面的#,并在冒号后面添加SimHei font.sans-serif : SimHei, DejaVu Serif, Bitstream Vera Serif, Computer Modern Roman, New Century Schoolbook, Century Schoolbook L, Utopia, ITC Bookman, Bookman, Nimbus Roman No9 L, Times New Roman, Times, Palatino, Charter, serif # 去掉前面的#,并将True改为False axes.unicode_minus : False |
4. 删除matplotlib缓存
matplotlib的缓存路径为"/Users/XXXX/.matplotlib",如果不知道自己的缓存路径,可以使用如下python命令,在终端查看
1 2 | import matplotlib matplotlib.get_cachedir() |
然后在终端使用命令“rm -rf 路径”删除缓存
5. 重启python