Skip to content
Advertisement

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:

JavaScript

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:

resulting pie chart

Dataframe: https://cdn.discordapp.com/attachments/925138838588911626/932369853220810833/unknown.png

Advertisement

Answer

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:

JavaScript

reordering pie chart wedges in pandas

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement