2017-10-11 269 views
1

我想繪製一個餅圖,顯示超過1%的貢獻及其對應的圖例標籤。如何根據貢獻值在pyplot餅圖中顯示已過濾的圖例標籤?

我已經管理顯示餅圖上我想要的百分比值(請參閱下面的腳本),但不是圖例標籤。在下面的例子中,我想顯示圖例標籤ABCD,但不是EF。

我嘗試了幾件事情,但只能顯示完整的圖例或帶有無可比擬(錯誤)顏色的過濾圖例。

我該怎麼做?有人可以幫忙嗎?謝謝。

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

回答

0

你也可以遍歷數據幀值(可能歸一化,如果他們沒有的話),只需要對那些大於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

傳說手柄和標籤
相關問題