繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM