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.

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)
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()])

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With