matplotlib 畫圖時(shí)中文亂碼問題的解決

一、報(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è)置正常顯示符號

這兩句可以注釋掉了。

參考資料:
https://www.cnblogs.com/swiftyao/p/14200373.html

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容