Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change autopct label position on matplotlib pie chart

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. enter image description here

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

like image 832
doug Avatar asked Mar 20 '15 12:03

doug


1 Answers

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): a diagram

like image 198
Andrey Sobolev Avatar answered Sep 19 '22 15:09

Andrey Sobolev