With ax = squarify.plot(...)
, ax.patches
包含一个列表矩形贴片 https://matplotlib.org/3.2.0/api/_as_gen/matplotlib.patches.Rectangle.html。这些矩形具有诸如get_x()
。坐标位于轴坐标系中,在 x 和 y 方向上似乎都是从 0 到 100。
当您在同一图中绘制更多元素时,ax
可能还包含其他元素,因此您可能需要过滤它们。
import matplotlib.pyplot as plt
import squarify # pip install squarify (algorithm for treemap)
ax = squarify.plot(sizes=[13, 22, 35, 5], label=["group A", "group B", "group C", "group D"], color=['b','r','y','g'])
for rect in ax.patches:
x, y, w, h = rect.get_x(), rect.get_y(), rect.get_width(), rect.get_height()
c = rect.get_facecolor()
print(f'Rectangle x={rect.get_x()} y={rect.get_y()} w={rect.get_width()} h={rect.get_height()} ')
plt.axis('off')
plt.show()
PS: To obtain the corresponding texts, again supposing the plot only contains the treemap:
for rect, text in zip(ax.patches, ax.texts):
x, y, w, h = rect.get_x(), rect.get_y(), rect.get_width(), rect.get_height()
c = rect.get_facecolor()
t = text.get_text()