天天看點

用matplotlib繪圖出現中文亂碼UserWarning: findfont: Font family [‘sans-serif‘] not found.

matplotlib 繪圖中文亂碼

下載下傳中文字型并放到指定目錄中

​​​下載下傳位址​​ 檢視自己所用matplotlib庫所在路徑,把字型檔案放入相應的字型檔案夾中

import matplotlib 
print(matplotlib.matplotlib_fname())      
用matplotlib繪圖出現中文亂碼UserWarning: findfont: Font family [‘sans-serif‘] not found.

在/home/xt/anaconda3/envs/dip/lib/python3.6/site-packages/matplotlib/mpl-data/fonts/ttf目錄中,字型放在這個目錄中還需要修改配置檔案,這個檔案就是matplotlibrc

matplotlibrc 在mpl-data路徑下面,粘貼下列到配置檔案

font.family         : sans-serif
font.sans-serif     : SimHei, DejaVu Sans, Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif
axes.unicode_minus  : False   #解決負号’-'顯示為方塊的問題      

運作的代碼裡面加入

matplotlib.rcParams['font.sans-serif'] = ['SimHei']  # 用黑體顯示中文
matplotlib.rcParams['axes.unicode_minus'] = False      

再去把系統的緩存清理掉,這個緩存檔案夾在ubuntu裡面是不可見的,但是可用終端進去

緩存檔案在/home/使用者名

在這個路徑下cd 到緩存檔案夾

windows使用者應該在user檔案夾中,.matplotlib

cd .cache/matplotlib
然後删除該檔案夾下的檔案
sudo rm -rf  檔案名      

然後跑代碼,如果不行,試試下面的

修改font_manager.py

/home/xt/anaconda3/envs/dip/lib/python3.6/site-packages/matplotlib/ 下可以找到這個

具體修改操作是:打開檔案後,直接找 self.defaultFamily,進行修改為我們的 SimHei 檔案,注意那個 afm 要保留,它是另一種字型檔案。

将檔案中的DejaVu Sans修改成SimHei:

用matplotlib繪圖出現中文亂碼UserWarning: findfont: Font family [‘sans-serif‘] not found.

還需要找到配置檔案中找到DejaVuSans.ttf并将其修改為SimHei.ttf:

用matplotlib繪圖出現中文亂碼UserWarning: findfont: Font family [‘sans-serif‘] not found.