Matplotlib 顯示中文 for Mac

歡迎Follow我的GitHub,關(guān)注我的簡(jiǎn)書(shū)

在Matplotlib中, 無(wú)法顯示中文, 需要修改配置文件.

1. 檢查中文字體

在Focus Search (聚焦搜索)中, 搜索"font", 進(jìn)入字體冊(cè), 選擇合適的字體集.

字體

如"黑體-簡(jiǎn)", 右鍵在"Folder (訪(fǎng)達(dá))"中顯示, 選擇粗體(Medium), 獲取路徑.

字體文件

復(fù)制路徑"option + command + c"

/System/Library/Fonts/STHeiti Medium.ttc

2. 修改Matplotlib配置

查看matplotlib的配置路徑:

import matplotlib
print matplotlib.matplotlib_fname() # 將會(huì)獲得matplotlib包所在文件夾

路徑:

/Users/xxxx/.matplotlib

修改配置中的字體文件fontList.json. 在ttflist列表中, 添加"Heiti"的中文字體集.

  "ttflist": [
    {
      "style": "normal",
      "name": "Heiti",
      "weight": 400,
      "fname": "/System/Library/Fonts/STHeiti Medium.ttc",
      "stretch": "normal",
      "_class": "FontEntry",
      "variant": "normal",
      "size": "scalable"
    },
  ...

查看matplotlib支持的字體集.

import matplotlib  
a=sorted([f.name for f in matplotlib.font_manager.fontManager.ttflist])  
  
for i in a:  
    print i  

"Heiti"字體集設(shè)置完成!

3. 使用字體集

設(shè)置font.family域?yàn)镠eiti.

plt.rcParams['font.family'] = ['Heiti']

線(xiàn)圖, 標(biāo)簽(label)和標(biāo)題(title)使用中文, 注意unicode.

t = np.arange(0.0, 2.0, 0.01)  # 值得范圍 0.0~2.0
s = 1 + np.sin(2 * np.pi * t)  # y = 1 + sin(2*Pi*x), 范圍頁(yè)是0~2

fig, ax = plt.subplots()  # 圖像fig和軸ax
ax.plot(t, s)  # 設(shè)置x軸和y軸

ax.set(xlabel=u'時(shí)間(秒)', ylabel=u'電壓(mV)',
       title=u'線(xiàn)圖')  # x軸文字, y軸文字, 標(biāo)題
ax.grid()  # 網(wǎng)格

print tmp_wrapper("demo_1.png")
fig.savefig(tmp_wrapper("demo_1.png"))  # 存儲(chǔ)圖片
plt.show()  # 顯示

顯示

中文圖

完美顯示, Perfect!!!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容