問題描述
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus']=False
使用matplotlib畫圖時,因為缺少字體,、圖像上label上的中文顯示時空白小方塊。因為matplotlib默認沒有中文。
解決方法:
Step 1. 在終端進入python3環(huán)境,查看matplotlib字體路徑:
import matplotlib
print(matplotlib.matplotlib_fname())

找到自己的matplotlib字體文件路徑:
/Users/zhangzhang/miniforge3/envs/py38_pytorch/lib/python3.8/site-packages/matplotlib/mpl-data/fonts/ttf
(這里的路徑與上面找出來的路徑不一致,需要手動刪除matplotlibrc,并添加fonts/ttf)
Step 2. 下載SimHei.ttf字體:
國內(nèi)SimHei:https://www.duote.com/soft/915316.html
下載后,解壓,并命名為SimHei.ttf
Step 3. 將下載好的SimHei.ttf字體移動到第一步查詢到的字體目錄./fonts/ttf/下:
mv 下載路徑 目標(biāo)路徑
mv /Users/zhangzhang/Downloads/SimHei.ttf /Users/zhangzhang/miniforge3/envs/py38_pytorch/lib/python3.8/site-packages/matplotlib/mpl-data/fonts/ttf
(也可以手動找出路徑,手動移)
Step 4. 打開終端,進入python環(huán)境,清理matplotlib緩沖目錄:
import matplotlib
print(matplotlib.get_cachedir())
獲取緩沖目錄地址:/Users/zhangzhang/.matplotlib
終端輸入exit()退出python環(huán)境,再刪除上面找到的緩沖文件:
rm -rf /Users/dan/.matplotlib
Step 5. 修改原始文件:
打開第一步找到的路徑:/Users/zhangzhang/miniforge3/envs/py38_pytorch/lib/python3.8/site-packages/matplotlib/mpl-data/matplotlibrc進行修改:

通過/定位(例如/font.sans-serif來定位),來修改下面三個地方:文章來源:http://www.zghlxwxcb.cn/news/detail-412162.html
#去掉前面的#
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 # use Unicode for the minus symbol rather than hyphen. See# https://en.wikipedia.org/wiki/Plus_and_minus_signs#Character_codes
Step 6. 重啟,測試。 (此時默認顯示中文字體)
import matplotlib.pyplot as plt
plt.title('顯示中文')
x = np.arange(7)
y = x
plt.plot(x, y, 'r-')
plt.xlabel('x軸')
plt.ylabel('y軸')
plt.show()

不需要plt.rcParams['font.sans-serif'] = ['SimHei']就可以自動顯示中文,至此中文顯示的問題已經(jīng)解決。文章來源地址http://www.zghlxwxcb.cn/news/detail-412162.html
到了這里,關(guān)于Mac系統(tǒng)下matplotlib中SimHei中文字體缺失報錯的解決辦法的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!