Change autopct label position on matplotlib pie chart

心已入冬 提交于 2019-12-12 16:17:29

问题


I'm plotting some pie charts in matplotlib and the percentage labels on some of my charts overlap each other and look messy. Is there a way to change the position of the text so it is all readable? And example of what I'm getting is below - the category 'Others' and 'ALD2_OH' are overlapping and are unreadable.

My plotting code is here:

matplotlib.rcParams.update({'font.size': 18})
plt.figure(figsize=(11,11))

labels = ['ALD2 + OH','PAN + $therm$','ALD2 + NO$_3$','ATOOH + $hv$',
          'Others',]

colours = ['BlueViolet','DarkMagenta','DarkOrchid','DarkViolet','Purple'
           ]

patches, texts,autotexts = plt.pie(main_producers, labels=labels, colors = colours,
        autopct='%1.1f%%', startangle = 90)

plt.title('Contribution to MCO$_3$ yeild')

Hope someone can help!

Thanks


回答1:


You might want to move autotexts of narrow wedges from the center of the wedge along the radius:

for patch, txt in zip(patches, autotexts):
    # the angle at which the text is located
    ang = (patch.theta2 + patch.theta1) / 2.
    # new coordinates of the text, 0.7 is the distance from the center 
    x = patch.r * 0.7 * np.cos(ang*np.pi/180)
    y = patch.r * 0.7 * np.sin(ang*np.pi/180)
    # if patch is narrow enough, move text to new coordinates
    if (patch.theta2 - patch.theta1) < 10.:
        txt.set_position((x, y))

This yields (I simulated your data to some extent):



来源:https://stackoverflow.com/questions/29166508/change-autopct-label-position-on-matplotlib-pie-chart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!