當(dāng)在MacBook的pycharm上使用matplotlib繪制圖表時(shí),中文很可能會(huì)無法正常顯示,如下圖中圖表文字部分的方塊:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-2, 6, 50)
y1 = x + 3 # 曲線 y1
plt.figure() # 定義一個(gè)圖像窗口
plt.plot(x, y1) # 繪制曲線 y1
plt.title('直線圖')
plt.show()

解決辦法:
查看matplotlib支持的字體集
from matplotlib import font_manager
ttf_lists = font_manager.fontManager.ttflist
for font in ttf_lists:
print(font)
<Font 'Songti' (Songti.ttc) normal normal 400 normal>
<Font 'STIXSizeFourSym' (STIXSizFourSymBol.ttf) normal normal bold normal>
<Font 'STIXSizeThreeSym' (STIXSizThreeSymBol.ttf) normal normal bold normal>
<Font 'STIXNonUnicode' (STIXNonUniIta.ttf) italic normal 400 normal>
<Font 'STIXGeneral' (STIXGeneralBol.ttf) normal normal bold normal>
從中選擇一種中文字體,以宋體為例:
plt.rcParams['font.sans-serif']=['Songti']
plt.rcParams['axes.unicode_minus']=False
這樣就可以顯示成功了,如下圖

注意:如果查看的字體集宋體為如下所示:
<Font 'Songti SC' (Songti.ttc) normal normal 400 normal>
<Font 'STIXSizeFourSym' (STIXSizFourSymBol.ttf) normal normal bold normal>
<Font 'STIXSizeThreeSym' (STIXSizThreeSymBol.ttf) normal normal bold normal>
<Font 'STIXNonUnicode' (STIXNonUniIta.ttf) italic normal 400 normal>
<Font 'STIXGeneral' (STIXGeneralBol.ttf) normal normal bold normal>
那么上面語句應(yīng)該為
# plt.rcParams['font.sans-serif']=['Songti']
plt.rcParams['font.sans-serif']=['Songti SC']
plt.rcParams['axes.unicode_minus']=False
如果查看的matplotlit字體集中沒有宋體,然后你想使用宋體,則需要修改matplotlit配置文件,具體操作如下
-
查看Mac中文字體集
在Focus Search (聚焦搜索)中, 在電腦屏幕右上角點(diǎn)擊搜索圖標(biāo),搜索font, 進(jìn)入字體冊(cè), 選擇宋體(沒有宋體,那你就需要下載該字體了)
如宋體-簡(jiǎn), 選擇常規(guī)體, 右鍵在Folder (訪達(dá))中顯示,獲取路徑(右鍵,顯示簡(jiǎn)介)復(fù)制路徑 option + command + c
/Library/Fonts/Songti.ttc
- 修改Matplotlib配置
進(jìn)入matplotlib的配置路徑
cd /User/xxxx/.matplotlib
修改配置中的字體文件fontList.json,在ttflist列表中, 添加"Songti"的中文字體集。首先,進(jìn)入fontList.json
vi fontList.json
找到ttflist
/ttflist
添加宋體字體集
{
"fname": "/Library/Fonts/Songti.ttc",
"name": "Songti",
"style": "normal",
"variant": "normal",
"weight": 400,
"stretch": "normal",
"size": "scalable",
"_class": "FontEntry"
}
查看matplotlib支持的字體集,這時(shí)候就顯示有"Songti"了 (當(dāng)然上述的"Songti SC"也可以在這里改為"Songti" ,如果你不嫌麻煩,也可以不改,按照上面??的語句也可以使用),設(shè)置就完成了!
- 使用字體集
plt.rcParams['font.sans-serif']=['Songti']
plt.rcParams['axes.unicode_minus']=False
參考:
1、matplotlib顯示中文 for mac
2、Python-MacOS上matplotlib顯示中文字體

