如何在树状图上添加 % 信息?

How to add % information on a treemap?

我正在绘制树图,想知道如何绘制树的相对百分比 class,即

A​​组=100
地面 B =30
地面 C =50
地面D =20

那么,在plot中,应该加上:
A 组的“50%”
B 组的“15%”
等在其 'Group 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 )

无论哪种方式,最终结果都将与此类似: