Matplotlib 饼状图中的文字中文乱码问题

ChesterZubi 9年前

来自: 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'))

修改后饼状图图形中的中文乱码可以解决了: