1
votes

I would like to plot a pie chart that shows contributions that are more than 1%, and their corresponding legend label.

I have managed showing the percentage values I wanted on the pie (see script below), but not the legend labels. In the following example, I want to show legend labels ABCD, but not EF.

I have tried several things, but only able to show either a full legend, or a filtered legend with unmatched (wrong) colors.

How can I do this? Can someone help? Thanks.

sizes = pd.DataFrame([80,10,5,4,0.1,0.9],index=list("ABCDEF"))

fig1, ax2 = plt.subplots()

def autopct_more_than_1(pct):
    return ('%1.f%%' % pct) if pct > 1 else ''

ax2.pie(sizes.values, autopct=autopct_more_than_1)
ax2.axis('equal') 

plt.legend(sizes.index, loc="best", bbox_to_anchor=(1,1))

plt.show()
1

1 Answers

1
votes

You can loop over the dataframe values (possibly normalized if they aren't already) and only take the legend handles and labels for those which are bigger than 1.

import matplotlib.pyplot as plt
import pandas as pd

sizes = pd.DataFrame([80,10,5,4,0.1,0.9],index=list("ABCDEF"))

fig1, ax = plt.subplots()

def autopct_more_than_1(pct):
    return ('%1.f%%' % pct) if pct > 1 else ''

p,t,a = ax.pie(sizes.values, autopct=autopct_more_than_1)
ax.axis('equal') 

# normalize dataframe (not actually needed here, but for general case)
normsizes = sizes/sizes.sum()*100
# create handles and labels for legend, take only those where value is > 1
h,l = zip(*[(h,lab) for h,lab,i in zip(p,sizes.index.values,normsizes.values) if i > 1])

ax.legend(h, l,loc="best", bbox_to_anchor=(1,1))

plt.show()

enter image description here