Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep same color for each label in different pie charts

I'm having trouble keeping the same color for every label from one pie chart to another. As you can see in the image below, Matplotlib inverts the colors in the 2nd pie chart.I would like to keep red for the 'Frogs' label and green for the 'Hogs' label. I also tried to add the label parameter but then it just gives the wrong count. I also tried to reverse the colors in the 2nd chart with colors=colors[::-1]it works but is not sustainable because sometimes I have more than two labels.

enter image description here

Here's the code:

sizes1 = ['Frogs', 'Hogs', 'Frogs', 'Frogs']
sizes2 = ['Hogs', 'Hogs', 'Hogs', 'Frogs', 'Frogs']

colors=['red', 'green']

df1 = pd.DataFrame(data=sizes1, columns=['a'])
df2 = pd.DataFrame(data=sizes2, columns=['a'])

fig, ax = plt.subplots(1, 2, figsize=(18,5))


df1['a'].value_counts().plot.pie(explode=[0,0.1],autopct='%1.1f%%',ax=ax[0],shadow=True, colors=colors)
df2['a'].value_counts().plot.pie(explode=[0,0.1],autopct='%1.1f%%',ax=ax[1],shadow=True, colors=colors)

like image 436
mobelahcen Avatar asked Oct 24 '25 00:10

mobelahcen


1 Answers

You can define a color dictionary and then use this mapping to assign the colors while plotting. This will keep the color scheme consistent across all the subplots.

colors={'Frogs':'red', 
        'Hogs':'green'}

df1['a'].value_counts().plot.pie(explode=[0,0.1],autopct='%1.1f%%',ax=ax[0],shadow=True, 
                                 colors=[colors[v] for v in df1['a'].value_counts().keys()])
df2['a'].value_counts().plot.pie(explode=[0,0.1],autopct='%1.1f%%',ax=ax[1],shadow=True, 
                                 colors=[colors[v] for v in df2['a'].value_counts().keys()])

enter image description here

like image 89
Sheldore Avatar answered Oct 26 '25 18:10

Sheldore