使用仿射变换添加PatchCollection

4

我有一些 patches,我会在 matplotlib 中应用不同的 Affine2D 变换。 是否可能将它们作为 collections.PatchCollection 添加? 不知何故,我只能在每个 patch 上单独调用 ax.add_patch() 才能绘制它们。

from matplotlib import pyplot as plt, patches, collections, transforms

fig, ax = plt.subplots()

trafo1 = transforms.Affine2D().translate(+0.3, -0.3).rotate_deg_around(0, 0, 45) + ax.transData
trafo2 = transforms.Affine2D().translate(+0.3, -0.3).rotate_deg_around(0, 0, 65) + ax.transData

rec1 = patches.Rectangle(xy=(0.1, 0.1), width=0.2, height=0.3, transform=trafo1, color='blue')
rec2 = patches.Rectangle(xy=(0.2, 0.2), width=0.3, height=0.2, transform=trafo2, color='green')

ax.add_collection(collections.PatchCollection([rec1, rec2], color='red', zorder=10))

# ax.add_patch(rec1)
# ax.add_patch(rec2)

enter image description here

1个回答

2
看起来PatchCollection不支持单独变换元素。从Matplotlib文档中,我们可以了解到Collection是一个用于有效绘制共享大多数属性的大量对象的类,例如大量线段或多边形。您可以通过创建没有任何单独变换补丁的集合来理解这一点:
rec1 = patches.Rectangle(xy=(0.1, 0.1), width=0.2, height=0.3, color='blue')
rec2 = patches.Rectangle(xy=(0.2, 0.2), width=0.3, height=0.2, color='green')
col = collections.PatchCollection([rec1, rec2], color='red', zorder=10)
print(col.get_transform())

打印最后一个语句IdentityTransform(),并且正确显示(未变换的)补丁。这些补丁可以从PatchCollection中一次性变换,而无需单独指定。

相反,当你为每个补丁应用单独的变换(就像在你的情况下),.get_transform()方法返回一个空列表。这可能是因为PatchCollection类是为了加速绘图效率(如上所述),包括transform属性,而收集具有许多共同属性的patches

注意:在这个答案中,您可以找到一个解决办法,通过将patch转换为path,然后转换为PathCollection,与单个补丁绘制相比,可以提高绘图效率。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接