Search code examples
pythonpie-chart

python pie chart: how to NOT order the wedges by value


I created a pie chart.

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)

Then I plotted the pie chart.

import matplotlib.pyplot as plt
fig, ax=plt.subplots()
values2=df['T2'].value_counts()
ax.pie(values2, radius=1.3, autopct= lambda x: '{:.0f}'.format(x*values2.sum()/100))

Python is ordering the wedges from low to high value. I want to order it by the name of the value (alphabetically).

I tried the following:

ax.pie(values2, radius=1.3, autopct= lambda x: '{:.0f}'.format(x*values2.sum()/100), labels=values2.index)

But that doesn't change anything but plotting the labels on the wedges. I hope I can describe understandable what I want to do. I think it must be easy? enter image description here


Solution

  • You don't need to sort the index value with pie chart library, just change:

    values2=df['T2'].value_counts()
    

    to

    values2=df['T2'].value_counts().sort_index()
    

    for sorting the index from dataframe.