How do I rearrange the order of pie slices in pandas plot?
I am trying to rearrange the order of the pie slices in my pie chart. I am relatively new to Python and am having trouble figuring this out. Here is my current code:
df.groupby(['Country']).sum().plot(kind='pie', y='Alcohol_Consumption', subplots=True, shadow = True,startangle=-270,
figsize=(15,10), autopct='%1.1f%%', counterclock=False,)
plt.show()
The pie chart slices arrange in alphabetical order by the names of the countries, even though my dataframe is different. So, how do I change the order of the pie chart slices to be the same as the dataframe?
Here is the resulting pie chart:
Dataframe: https://cdn.discordapp.com/attachments/925138838588911626/932369853220810833/unknown.png
Solution 1:
If each country only appears once in your dataframe, you could try df.set_index('Country').plot(kind='pie', y='Alcohol_Consumption')
. If each country appears multiple times, you could use df['Country'] = pd.Categorical(df['Country'], df['Country'].unique())
to force the existing ordering as a fixed ordering on that column.
Here is a simplified example:
import matplotlib.pyplot as plt
import pandas as pd
fig, (ax1, ax2, ax3) = plt.subplots(ncols=3, figsize=(14, 4))
df = pd.DataFrame({'Country': ['c', 'b', 'a'],
'Consumption': [1, 2, 3]})
df.groupby('Country').sum().plot(kind='pie', y='Consumption', ax=ax1)
ax1.set_title('Just using groupby')
df.set_index('Country').plot(kind='pie', y='Consumption', ax=ax2)
ax2.set_title('Using set_index()\nsupposes Country is unique')
df['Country'] = pd.Categorical(df['Country'], df['Country'].unique())
df.groupby('Country').sum().plot(kind='pie', y='Consumption', ax=ax3)
ax3.set_title('Using groupby, order\nforced via pd.Categorical')
plt.tight_layout()
plt.show()