[英]How to add % information on a treemap?
I am plotting a treemap and was wondering how to also plot the relative percentage of a tree class, ie我正在绘制树形图,想知道如何绘制树类的相对百分比,即
Group A =100 A组=100
Groun B =30 B地=30
Groun C =50地 C =50
Groun D =20地 D = 20
Then, in the plot, it should add:然后,在情节中,它应该添加:
'50%' for Group A A 组的“50%”
'15%' for Group B B 组为“15%”
etc. next to its 'Group X' label.等在其“X 组”标签旁边。 How would I do that given this code?鉴于此代码,我将如何做到这一点?
!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();
Assuming that the sum of all values gives 100%, you can change the labels and then plot the newly created labels instead or additional to your descriptors from the dataframe.假设所有值的总和为 100%,您可以更改标签,然后绘制新创建的标签来代替或从数据框中附加到您的描述符。
Print only percentage values:仅打印百分比值:
lbl = [str('{:5.2f}'.format(i/df['customers'].sum()*100)) + "%" for i in df['customers']]
squarify.plot(sizes=df['customers'], label=lbl, alpha=.8 )
Combined description and percentage values组合描述和百分比值
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 )
Update 2021-02-01更新 2021-02-01
As of python version 3.6 the preferred way of formatted string literals are f-strings
.从 python 3.6 版开始,格式化字符串文字的首选方式是f-strings
。 Most of the time, f-strings
are more compact and easier to read.大多数情况下, f-strings
更紧凑且更易于阅读。 The example with combined description and percentage information looks like this using 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 )
Either way the final result will look similar to this:无论哪种方式,最终结果都将类似于以下内容:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.