LaL*_*aTi 5 python python-3.x squarify
我正在绘制树形图,想知道如何绘制树类的相对百分比,即
A 组 =100
组 B =30
组 C =50
组 D =20
然后,在图中,它应该
在其“X 组”标签旁边添加:“
50%”用于 A 组,“
15%”用于 B 组
等。鉴于此代码,我将如何做到这一点?
!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();
Run Code Online (Sandbox Code Playgroud)
假设所有值的总和为 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 )
Run Code Online (Sandbox Code Playgroud)
组合描述和百分比值
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 )
Run Code Online (Sandbox Code Playgroud)
更新 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 )
Run Code Online (Sandbox Code Playgroud)
无论哪种方式,最终结果都将类似于以下内容:
归档时间: |
|
查看次数: |
1688 次 |
最近记录: |