假设所有值的总和为 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 )
无论哪种方式,最终结果都将与此类似:
