5

I was trying to create a pie chart in matplotlib and would like to put the labels within wedges. I used the following code to do it:

import matplotlib.pyplot as plt

fig = plt.figure(1, figsize=(8,8), dpi=60)
ax=fig.add_axes([0.1,0.1,0.8,0.8])
labels = ['label0','label1','label2','label3','label4','label5','label6','label7','label8',\
          'label0','label1','label2','label3','label4','label5','label6','label7','label8']
colors = list('w' for _ in range(18))
fracs=list(20 for _ in range(18))
ax.pie(fracs, labels=labels, colors = colors, startangle=10,labeldistance=0.8)
plt.show()

It seems that the labels are not properly aligned within wedges as shown in the image below. Is there any way to modify(or rotate) the labels so that they can be shown properly inside the wedges?

Thank you!

Matplotlib generated image

Ken Ma
  • 301
  • 1
  • 5
  • 13

1 Answers1

9

Adjusting the alignment of the labels after they are returned should do the trick:

patches, texts = ax.pie(fracs, labels=labels, colors = colors, 
                        startangle=10, labeldistance=0.8)
for t in texts:
    t.set_horizontalalignment('center')

plt.show()

I don't really understand the second question, as it seem you have already moved the slices by 10 degrees using the startangle parameter. It is typically better to list separate questions in different posts anyhow.

hackyday
  • 1,279
  • 8
  • 12
  • Thank you! That worked. As I moved the slices by 10 degree, I would like to label the degree number at the beginning of each slice. I will post this question separately. – Ken Ma Sep 05 '13 at 19:22
  • This is the new question I posted regarding the second question. http://stackoverflow.com/questions/18645059/matplotlib-pie-charts-label-to-indicate-slice-angles @hackyday – Ken Ma Sep 05 '13 at 20:12