这些矩形一起存储在一个BarContainer
. 默认情况下,matplotlib 为整个容器假设一个图例标签。要为每个单独的矩形添加图例标签,您可以将BarContainer
as 句柄传递给plt.legend()
.
下面的示例代码明确指定颜色,因为默认颜色可能有点难以区分。
from matplotlib import pyplot as plt
import squarify
sizes = [30, 15, 3]
labels = ['Largest Block\n(30 units)', 'Second Largest Block\n(15 units)', 'Small Block\n(3 units)']
ax = squarify.plot(sizes, alpha=.7, norm_x=10, color=plt.cm.Set2.colors)
ax.get_xaxis().set_visible(False)
from matplotlib import pyplot as plt
import squarify
sizes = [30, 15, 3]
labels = ['Largest Block\n(30 units)', 'Second Largest Block\n(15 units)', 'Small Block\n(3 units)']
ax = squarify.plot(sizes, norm_x=10, color=plt.cm.Set2.colors)
ax.get_xaxis().set_visible(False)
plt.legend(handles=ax.containers[0], labels=labels)
plt.show()

PS:要使图例与显示的矩形顺序相同,您可以反转 y 轴 ( ax.invert_yaxis()
) 或反转句柄和标签列表 ( plt.legend(handles=ax.containers[0][::-1], labels=labels[::-1])
)。
这是另一个示例,注释图中最大的矩形并在图例中显示最小的矩形:
from matplotlib import pyplot as plt
import squarify
import numpy as np
labels = [55, 34, 21, 13, 8, 5, 3, 2, 1, 1]
sizes = [f * f for f in labels]
num_labels_in_legend = 5
ax = squarify.plot(sizes, label=labels[:-num_labels_in_legend], color=plt.cm.plasma(np.linspace(0, 1, len(labels))),
ec='black', norm_x=144, norm_y=89, text_kwargs={'color': 'white', 'size': 18})
ax.axis('off')
ax.invert_xaxis()
ax.set_aspect('equal')
plt.legend(handles=ax.containers[0][:-num_labels_in_legend - 1:-1], labels=labels[:-num_labels_in_legend - 1:-1],
handlelength=1, handleheight=1)
plt.show()

这是计算要在图例中显示的标签数量的想法。例如,当小矩形的总面积小于总面积的 5% 时:
num_labels_in_legend = np.count_nonzero(np.cumsum(sizes) / sum(sizes) > 0.95)
或者只是小于总面积 2% 的矩形数量:
num_labels_in_legend = np.count_nonzero(np.array(sizes) / sum(sizes) < 0.02)