0

I plotted a pie chart and rotate the labels:

import pandas as pd
import matplotlib.pyplot as plt
data = { 'T1': [1,1,1,1,1,2,2,2,2,2, 1,1,1,1,1, 2,2,2,2,2, 1,1,1,1,1, 2,2,2,2],
         'T2':['A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A',
               'B','B', 'B', 'B', 'B', 'B',
               'C', 'C', 'C', 'C','C', 'C', 'C',
              'D', 'D', 'D', 'D']}
df = pd.DataFrame(data)
df['T1']=df['T1'].astype(str)
fig, ax=plt.subplots()
values2=df['T2'].value_counts().sort_index()
pie1=ax.pie(values2, radius=1.3, autopct='%1.1f%%', labeldistance=0.4,   
       labels=['one', 'two', 'three', 'four'], rotatelabels=True, startangle=223.5, wedgeprops=dict(width=1, edgecolor='w'));
for tx in pie1[1]:
    rot = tx.get_rotation()
    tx.set_rotation(rot+90+(1-rot//180)*180)
hole = plt.Circle((0, 0), 0.5, facecolor='white')
plt.gcf().gca().add_artist(hole)
plt.show()

example pie chart

I can't use startangle a 2nd time to rotate the percentages. How can I do this to give the pie chart a better look?

Now I tried to use:

for tx in pie1[2]:
    rotate = tx.get_rotation()
    tx.set_rotation(rotate+90+(1-rotate//180)*180)

Because I understood that the 2 in pie2 refers to the autopct (am I right?). But then the percentages are rotated in a different way than the labels. Has anyone an idea why? enter image description here

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Kajette
  • 47
  • 4

1 Answers1

1

The pie returns a tuple of lists :

patches : list
A sequence of matplotlib.patches.Wedge instances

texts : list A list of the label Text instances.

autotexts : list
A list of Text instances for the numeric labels. This will only be returned ..

So you can unpack it and rotate the labels/percentages in // :

p, t, a = ax.pie(
    values2, radius=1.3, autopct='%1.1f%%', labeldistance=0.4,
    labels=['one', 'two', 'three', 'four'], rotatelabels=True, startangle=223.5,
    wedgeprops=dict(width=1, edgecolor='w')
)

for tx, pc in zip(t, a):
    rot = tx.get_rotation()
    tx.set_rotation(rot+90+(1-rot//180)*180)
    pc.set_rotation(tx.get_rotation())

Output :

enter image description here

Timeless
  • 22,580
  • 4
  • 12
  • 30