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

Osc*_*sca 1 matplotlib pandas squarify

我有一个数据框,我想用它来绘制树图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)
Run Code Online (Sandbox Code Playgroud)
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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

预期输出将在图表上同时出现counts和。country_name

Joh*_*anC 5

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


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()
Run Code Online (Sandbox Code Playgroud)

具有组合标签的方形图