MacOS系統下matplotlib中SimHei中文字體無法啟動解決辦法
- 遇到的問題
- 解決辦法
遇到的問題
matplotlib默認字體沒有中文

所以需要使用以下代碼呼叫中文字體:
plt.rcParams['font.sans-serif'] = ['SimHei']
在呼叫的程序中可能出現如下情況:

解決辦法
一、查看matplotlib字體路徑
這里提供兩種方法:
1、終端查看:
在終端中進入python3環境,然后輸入
import matplotlib
print(matplotlib.matplotlib_fname())
找到自己的matplotlib字體檔案夾路徑
2、PyCharm或Jupyter
創建python檔案(以Jupyter舉例),輸入以下代碼查看路徑
import matplotlib
print(matplotlib.matplotlib_fname())
查詢結果如下所示:

二、下載SimHei字體
這里提供兩個下載鏈接:
1、國內字體下載網站
2、官網字體下載
三、將下載好的SimHei.ttf移動到第一步查詢到的目錄中:/Users/dengboyuan/opt/anaconda3/lib/python3.8/site-packages/matplotlib/mpl-data/fonts,注意名稱一定是SimHei.ttf
四、清理matplotlib緩沖目錄
打開終端,進入python環境,輸入
import matplotlib
print(matplotlib.get_cachedir())
獲取緩沖目錄地址:/Users/dengboyuan/.matplotlib

PyCharm和Jupyter同上,
在終端中輸入:exit()退出python環境
使用rm -rf 路徑洗掉緩沖檔案(注意空格):

五、修改原始檔案
打開路徑:/Users/dengboyuan/opt/anaconda3/lib/python3.8/site-packages/matplotlib/mpl-data找到matplotlibrc檔案做以下修改:
font.family: sans-serif
#去掉前面的#
font.sans-serif: SimHei, DejaVu Sans, Bitstream Vera Sans, Computer Modern Sans Serif, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif
#去掉前面的#,手動添加SimHei
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
#去掉前面的#,把True改為False
六、重啟Jupyter

不需要plt.rcParams['font.sans-serif'] = ['SimHei']就可以自動顯示中文,至此中文顯示的問題已經解決,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/258183.html
標籤:python
上一篇:普歌-碼靈團隊:MySQL資料庫中的簡單測驗框架-計算器測驗框架
下一篇:單調堆疊演算法
