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

标签 python python-3.x squarify

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

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

然后,在图中,应该添加:
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();

enter image description here

最佳答案

假设所有值的总和为 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-string 更紧凑且更易于阅读。使用 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 )
<小时/>

无论哪种方式,最终结果都会类似于:

enter image description here

关于python - 如何在树状图上添加%信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57914782/

相关文章:

python - 文本中的多个词索引

python - 无法在 python 2.7 上安装 pip,只有 python 3

python - 为什么 pyautogui 点击实际上没有点击

python - 如何关闭 Python 正在使用的 mp3 文件?

python - 在 Django 中创建 OneToMany 模型

python - 在这种情况下如何使用 get_dummies() ?

python - 更新 html 中的文本