Matplotlib 中文字體無法顯示的解決方法

Pei Lee
2 min readJun 19, 2018

--

需求描述:讓中文能正常顯示在 Matplotlib 畫出來的圖上,有先 Google 過,但可能是有改版,結果試完網路上的方法沒成功,稍微修改一下寫了一篇新的。

環境:macOS + Python 3.6

Matplotlib 中文無法顯示,主要是因為預設的字體認不得中文,因此只要稍微改一下設定就可以了。

一、下載認得中文的字體

黑體字體下載:黑體字體 simhei.ttf

貼到 ~/anaconda/lib/python3.6/site-packages/matplotlib/mpl-data/fonts/ttf/.

另外有看到用 Jupyter Lab 的人路徑會有點不一樣,可以用以下方式確認路徑:

import matplotlibmatplotlib.matplotlib_fname()

二、刪掉目前的 cache

把原本的暫存檔刪掉:

cd ~/.matplotlibrm -rf fontList.jsonrm -rf tex.cache

三、改文件

nano ~/anaconda/lib/python3.6/site-packages/matplotlib/mpl-data/matplotlibbrc

找到 font.family : sans-serif,把前面的 # 刪掉;接著找到 font.sans-serif,把前面的 # 刪掉,並把剛才放進去的字體 simhei 放在冒號後面(注意大小寫)。

font.sans-serif     : simhei, ........(後略)

接著重啟 server 後,理論上應該就可以了。

--

--

Pei Lee
Pei Lee

Written by Pei Lee

Data Team Lead @ Retail & E-commerce Industry

No responses yet