一、報(bào)錯信息
RuntimeWarning: Glyph 20108 missing from current font. font.set_text(s, 0.0, flags=flags)
原因:matplotlib中文亂碼
二、解決方法
1、有中文字體
直接加入下面的兩行代碼即可正常顯示
plt.rcParams['font.sans-serif'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False ## 設(shè)置正常顯示符號
2、無中文字體
此時(shí)加入上面兩行代碼后依舊報(bào)錯。處理方法是:
1)找到 python 中保存字體的目錄
C:\Users\xxxxx>python
Python 3.7.0 (default, Jun 28 2018, 08:04:48) [MSC v.1912 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>import matplotlib
>>>print(matplotlib.matplotlib_fname())
D:\Anaconda531\lib\site-packages\matplotlib\mpl-data\matplotlibrc
2)下載并保存字體文件
在網(wǎng)上搜一下相應(yīng)的 .ttf 格式字體文件(比如這里的 SimHei 字體),隨便找個(gè)網(wǎng)站下載,然后文件放入以下目錄。
D:\Anaconda531\Lib\site-packages\matplotlib\mpl-data\fonts\ttf
3)清理舊緩存文件
在python環(huán)境中查看緩存文件的路徑。
>>> import matplotlib
>>> matplotlib.get_cachedir()
'C:\\Users\\xxxxx\\.matplotlib'
將這個(gè)緩存目錄刪掉。
4)修改配置文件 matplotlibrc
D:\Anaconda531\Lib\site-packages\matplotlib\mpl-data\matplotlibrc
將這個(gè)配置文件(沒有擴(kuò)展名的)打開,修改以下內(nèi)容
# 去掉 # 注釋
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
5)重新切換回 ide 中,運(yùn)行代碼。
正常情況下,這個(gè)時(shí)候應(yīng)該能夠解決問題。此時(shí),
plt.rcParams['font.sans-serif'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False ## 設(shè)置正常顯示符號
這兩句可以注釋掉了。