[英]How to add % information on a treemap?
我正在繪制樹形圖,想知道如何繪制樹類的相對百分比,即
A組=100
B地=30
地 C =50
地 D = 20
然后,在情節中,它應該添加:
A 組的“50%”
B 組為“15%”
等在其“X 組”標簽旁邊。 鑒於此代碼,我將如何做到這一點?
!pip install squarify
import squarify
df = pd.DataFrame({'customers':[8,3,4,2], 'cluster':["group A", "group B", "group C", "group D"] })
squarify.plot(sizes=df['customers'], label=df['cluster'], alpha=.8 )
plt.axis('off')
plt.show();
假設所有值的總和為 100%,您可以更改標簽,然后繪制新創建的標簽來代替或從數據框中附加到您的描述符。
僅打印百分比值:
lbl = [str('{:5.2f}'.format(i/df['customers'].sum()*100)) + "%" for i in df['customers']]
squarify.plot(sizes=df['customers'], label=lbl, alpha=.8 )
組合描述和百分比值
perc = [str('{:5.2f}'.format(i/df['customers'].sum()*100)) + "%" for i in df['customers']]
lbl = [el[0] + " = " + el[1] for el in zip(df['cluster'], perc)]
squarify.plot(sizes=df['customers'], label=lbl, alpha=.8 )
更新 2021-02-01
從 python 3.6 版開始,格式化字符串文字的首選方式是f-strings
。 大多數情況下, f-strings
更緊湊且更易於閱讀。 使用f-strings
組合描述和百分比信息的示例如下所示:
perc = [f'{i/df["customers"].sum()*100:5.2f}%' for i in df['customers']]
lbl = [f'{el[0]} = {el[1]}' for el in zip(df['cluster'], perc)]
squarify.plot(sizes=df['customers'], label=lbl, alpha=.8 )
無論哪種方式,最終結果都將類似於以下內容:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.