matplotlib預設字型設定

hibernake發表於2019-02-16

使用matplotlib的pyplot時,是支援unicode的,但預設字型是英文字型,導致中文無法正常顯示。
解決方法有兩種。

一種是手動指定,在程式碼中

from matplotlib.font_manager import FontProperties  
font_song = FontProperties(fname=r"c:windowsfontssimsun.ttc", size=15)

使用文字時指定引數 fontproperties=font_song 即可。

另一種是修改配置檔案中的預設字型,需要修改 matplotlibrc 檔案。
這一檔案的位置可以使用 matplotlib.matplotlib_fname() 檢視。
如果沒有修改會在site-package中。
在預設的matplotlibrc中有註釋,建議儲存在$HOME/.matplotlib/matplotlibrc下(win環境),防止在更新包時配置檔案被覆蓋。
通過 font.family : sans-serif 可以指定預設字型族為 sans-serif
之後在 font.sans-serif 的配置列表中最前加入中文字型即可。
但使用的中文字型應該為中文字型的名稱。
檢視系統的名稱可以通過font_manager檢視。
[ f.name for f in matplotlib.font_manager.fontManager.ttflist ]
[ f.name for f in matplotlib.font_manager.fontManager.afmlist ]
這兩個列表。
我使用的win10沒有SimSun(宋體),只能使用STSong,不知是何原因。
另外微軟官網字型裡也找不到win10資訊(官網連結)。

相關文章