永久解決 matplotlib 圖例中文方塊錯誤
永久解決 matplotlib 圖例中文方塊錯誤
- 問題
- 查看當前環境的字體路徑
- 解決方法
- 刪除緩存
原文鏈接:https://learnku.com/articles/41886
這里對原文做了點修改,因為原文還是有點小問題的
問題
當打印圖例的時候,圖可以正常顯示,但中文會顯示方塊。比如 title。然后會有個小報錯:
報錯描述:
/Users/username/anaconda3/lib/python3.6/site-packages/matplotlib/font_manager.py:
1331: UserWarning: findfont: Font family [‘SimHei’] not found. Falling
back to DejaVu Sans (prop.get_family(), self.defaultFamily[fontext]))
查看當前環境的字體路徑
import matplotlib
print(matplotlib.matplotlib_fname())
/Users/username/anaconda3/lib/python3.6/site-packages/matplotlib
解決方法
首先下載一個字體文件 SimHei.ttf 提取碼858y。
解壓字體后拷貝到 matplotlib/mpl-data/fonts/ttf 目錄下面。
mv ~/Downloads/SimHei.ttf ~/anaconda3/lib/python3.6/site-packages/matplotlib/mpl-data/fonts/ttf
修改配置文件 matplotlibrc:
vim ~/anaconda3/lib/python3.6/site-packages/matplotlib/mpl-data/matplotlibrc
found 這三項配置并修改:
font.family: sans-serif
font.sans-serif: SimHei, Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif
axes.unicode_minus: False # 解決負號'-'顯示為方塊的問題
前兩項大概在 194 行,第三項大概在 325 行。
但是改了配置之后并不會生效,需要重新加載字體,在 Python 中運行如下代碼即可
刪除緩存
print(matplotlib.get_cachedir())
rm -rf ~/.matplotlib
重啟jupyter,現在再打印圖例一點問題都沒有了,支持中英文混搭。

浙公網安備 33010602011771號