天天看點

matplotlib的預設字型_matplotlib預設字型設定

使用matplotlib的pyplot時,是支援unicode的,但預設字型是英文字型,導緻中文無法正常顯示。

解決方法有兩種。

一種是手動指定,在代碼中

from matplotlib.font_manager import FontProperties

font_song = FontProperties(fname=r"c:\windows\fonts\simsun.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資訊(官網連結)。