Ubuntu下Canopy matplotlib不顯示中文的解決方法。推薦方法二,一勞永逸!
方法一
步驟一:下載一箇中文字體,如msyh.ttf,拷貝到指定文件夾
$ sudo cp msyh.ttf /usr/share/fonts/truetype/
步驟二:在Canopy代碼中設置字體
zhfont = mpl.font_manager.FontProperties(fname='/usr/share/fonts/truetype/msyh.ttf')
步驟三:使用時,設置fontproperties
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.set_title(u'中文',fontproperties=zhfont)
Out[4]: <matplotlib.text.Text at 0x7fee34071050>
結果:
方法二
嘗試多次後終於找到直接從配置文件根本解決問題的方法!!!
步驟一:
找到matplotlibrc文件(先找到備用)(筆者安裝的是Canopy)
$HOME/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/matplotlib/mpl-data
步驟二:
在該目錄下的
../fonts/ttf
中添加,中文字體,如msyh.ttf,(對應的名字爲Microsoft YaHei。這個下面要用到。)
其他字體可以通過命令查找:
$ fc-list :lang=zh
/usr/share/fonts/opentype/noto/NotoSansCJK.ttc: Noto Sans CJK TC,Noto Sans CJK TC DemiLight:style=DemiLight,Regular
/usr/share/fonts/truetype/arphic/uming.ttc: AR PL UMing TW MBE:style=Light
/usr/share/fonts/truetype/arphic/ukai.ttc: AR PL UKai CN:style=Book
/usr/share/fonts/truetype/arphic/ukai.ttc: AR PL UKai HK:style=Book
留意後面對應的名字,如Noto Sans CJK TC,後面有用。
步驟三:
在matplotlibrc文件中找到
font.family : sans-serif
font.sans-serif : Microsoft YaHei,Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif
這兩行(Ctrl+F查詢即可),取消註釋,並添加“Microsoft YaHei,”,上面的代碼爲已添加後的代碼,保存退出。
步驟四:
按Ctrl+H顯示隱藏文件,會在$HOME下看到/.cache/文件夾:
$HOME/.cache/matplotlib
找到文件夾下的fontList.cache文件(原本里面並沒有msyh.ttf這個字體),刪除(每次啓動Canopy時,該文件會自動生成)。重啓後再查看該文件,就可以發現這個字體了。
最終成果
完成上述步驟,再次啓動Canopy,輸入代碼:
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.set_title(u'終於成功啦!')
Out[3]: <matplotlib.text.Text at 0x7fb7b4ef4dd0>
結果如下:
座標軸上的中文也可以顯示了: