使用 squareify.plot 在标签上显示多列值

问题描述

我有一个数据框,我想用 squarify 绘制树状图。我想通过编辑 country_name 参数在图表上显示 countslabels,但它似乎只取一个值。

示例数据

import squarify
import pandas as pd
from matplotlib import pyplot as plt
d = {'country_name':['USA','UK','Germany'],'counts':[100,200,300]}
dd = pd.DataFrame(data=d)
fig = plt.gcf()
ax = fig.add_subplot()
fig.set_size_inches(16,4.5)
norm = matplotlib.colors.normalize(vmin=min(dd.counts),vmax=max(dd.counts))
colors = [matplotlib.cm.Blues(norm(value)) for value in dd.counts]
squarify.plot(label=dd.country_name,sizes=dd.counts,alpha=.7,color=colors)
plt.axis('off')
plt.show()

enter image description here

预期输出将在图表上同时包含 countscountry_name

解决方法

您可以通过同时循环遍历两列并组合组合字符串来创建标签列表。例如:


import squarify
import pandas as pd
from matplotlib import pyplot as plt
import matplotlib

d = {'country_name': ['USA','UK','Germany'],'counts': [100,200,300]}
dd = pd.DataFrame(data=d)
labels = [f'{country}\n{count}' for country,count in zip(dd.country_name,dd.counts)]
fig = plt.gcf()
ax = fig.add_subplot()
fig.set_size_inches(16,4.5)
norm = matplotlib.colors.Normalize(vmin=min(dd.counts),vmax=max(dd.counts))
colors = [matplotlib.cm.Blues(norm(value)) for value in dd.counts]
squarify.plot(label=labels,sizes=dd.counts,alpha=.7,color=colors)
plt.axis('off')
plt.show()

squarify plot with combined labels

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...