Matplotlib 餅狀圖中的文字中文亂碼問題

ChesterZubi 8年前發布 | 13K 次閱讀 Python開發

來自: http://my.oschina.net/Kanonpy/blog/617535


今天用matplotlib畫餅狀圖時候遇到中文亂碼,一般遇到中文亂碼有兩種通用的解決方法,一種是修改matplotlibrc,通過修改matplotlibrc中的font.sans-serif添加中文,一種是直接在代碼中通過rcParams修改字體,既然遇到亂碼當然先用傳統方法試試,代碼如下:

 

 

可以看到雖然title的中文問題解決了,但是餅狀圖的中文依然顯示亂碼,下面試試修改matplotlibrc文件

遇到中文可以看出亂碼問題,然后嘗試了修改matplotlibrc文件,但是問題卻依然沒得到解決:

Lib\site-packages\matplotlib\mpl-data目錄,打開matplotlibrc文件,刪除font.familyfont.sans-serif兩行前的#,并在font.sans-serif后添加微軟雅黑字體(Microsoft YaHei),但是發現原來還是不行,究竟是什么問題呢?

______________________________________________________

 

后來發現ax.pie()函數返回值里面有text實例如下圖:

ax.pie(np.array(game_app["download_times"])[:5],labels=game_app["name"][:5],autopct='%1.1f%%')
×
Out[73]:
([<matplotlib.patches.Wedge at 0xd1b7450>,
  <matplotlib.patches.Wedge at 0xd4686f0>,
  <matplotlib.patches.Wedge at 0xd5757b0>,
  <matplotlib.patches.Wedge at 0xd58b4f0>,
  <matplotlib.patches.Wedge at 0xd58b950>],
 [<matplotlib.text.Text at 0xd531710>,
  <matplotlib.text.Text at 0xd575250>,
  <matplotlib.text.Text at 0xd575b90>,
  <matplotlib.text.Text at 0xd58b3d0>,
  <matplotlib.text.Text at 0xd58bd30>],
 [<matplotlib.text.Text at 0xd4689d0>,
  <matplotlib.text.Text at 0xd575450>,
  <matplotlib.text.Text at 0xd575f70>,
  <matplotlib.text.Text at 0xd58b690>,
  <matplotlib.text.Text at 0xd58bfb0>])

查看了一下text實例的fontname名稱,竟然不是Microsoft YaHei還是Bitstream Vera Sans,原來問題在這,圖形中的text實例并沒有受到影響:

a = ax.pie(np.array(game_app["download_times"])[:5],labels=game_app["name"][:5],autopct='%1.1f%%')
a[1][1].get_fontname()
Out[46]:
'Bitstream Vera Sans'

那么只能直接改text實例了,

pie = ax.pie(np.array(game_app["download_times"])[:5],labels=game_app["name"][:5],autopct='%1.1f%%')
#圖形中的文字無法通過rcParams設置
for font in pie[1]:
    font.set_fontproperties(mpl.font_manager.FontProperties(
            fname='L:/Python27/Lib/site-packages/matplotlib/mpl-data/fonts/ttf/simfang.ttf'))

修改后餅狀圖圖形中的中文亂碼可以解決了:

 本文由用戶 ChesterZubi 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!