今天用matplotlib画饼状图时候遇到中文乱码,通常遇到中文乱码有两种通用的解决方法,一种是修改matplotlibrc,经过修改matplotlibrc中的font.sans-serif添加中文,一种是直接在代码中经过rcParams修改字体,既然遇到乱码固然先用传统方法试试,代码以下:python
能够看到虽然title的中文问题解决了,可是饼状图的中文依然显示乱码,下面试试修改matplotlibrc文件面试
遇到中文能够看出乱码问题,而后尝试了修改matplotlibrc文件,可是问题却依然没获得解决:app
Lib\site-packages\matplotlib\mpl-data目录,打开matplotlibrc文件,删除font.family
和font.sans-serif
两行前的#
,并在font.sans-serif
后添加微软雅黑字体(Microsoft YaHei),可是发现原来仍是不行,到底是什么问题呢?函数
______________________________________________________字体
后来发现ax.pie()函数返回值里面有text实例以下图:spa
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实例并无受到影响:3d
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实例了,code
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'))
修改后饼状图图形中的中文乱码能够解决了:get