Home > Software design >  How do i get pie chart labels to line up with the correct values from dataframe?
How do i get pie chart labels to line up with the correct values from dataframe?

Time:01-09

My pie chart is coming out okay, the segments are the correct sizes, but the labels aren't on the correct places.

# declaring exploding pie
explode = [0, 0.1, 0, 0, 0,0]
# define Seaborn color palette to use
palette_color = sns.color_palette('pastel')
  
# plotting data on chart
fig=plt.pie(combined_df.groupby(['Continent'])['total_consumption'].sum(), colors=palette_color,labels=combined_df['Continent'].unique(),
        explode=explode, autopct='%.0f%%', labeldistance=0.9,)
plt.show

this is the result

the values that should be plotted

Continent
Africa           227.0
Asia             128.7
Europe           431.9
North America    147.5
Oceania           42.5
South America     83.2

CodePudding user response:

My suspicion is that the order of the returned results of unique() and value_counts() is not consistent.

value_counts() returned is order by count, and unique() is order by appearance in the array.

You can try this:

value_cnts = combined_df['Continent'].value_counts()
fig = plt.pie(value_cnts, colors=palette_color, labels=value_cnts.index, 
    explode=explode, autopct='%.0f%%', labeldistance=0.9)

CodePudding user response:

Try to not sort values on value_counts:

fig=plt.pie(combined_df['Continent'].value_counts(sort=False),  # <- do not sort
            colors=palette_color,
            labels=combined_df['Continent'].unique(),  # because unique is not sorted
            explode=explode, autopct='%.0f%%', labeldistance=0.9,)

Demo:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

palette_color = sns.color_palette('pastel')
explode = [0, 0.1, 0, 0, 0,0]

np.random.seed(2023)
data = data = np.random.choice(
    ['Africa', 'Asia', 'Europe', 'North America', 'Oceania', 'South America'],
    p=(0.213989, 0.121324, 0.407146, 0.139046, 0.040064, 0.078431),
    size=1000
)
combined_df = pd.DataFrame({'Continent': data})

fig = plt.pie(combined_df['Continent'].value_counts(sort=False), 
              autopct='%.0f%%', labeldistance=0.9, 
              labels=combined_df['Continent'].unique(),
              colors=palette_color, explode=explode)
plt.show()

enter image description here

  • Related