【问题标题】:Adding PatchCollection with Affine Transformations使用仿射变换添加 PatchCollection
【发布时间】:2020-09-26 23:57:02
【问题描述】:

我有一些patches,我在matplotlib 中应用了不同的Affine2D 转换。 是否有可能将它们添加为collections.PatchCollection?不知何故,我只能为它们每个单独调用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)

【问题讨论】:

    标签: python matplotlib affinetransform


    【解决方案1】:

    看起来PatchCollection 不支持单独转换的元素。从Matplotlib documentation,我们可以看出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类为了加快绘制效率(如前所述),将patches的很多公共属性集合起来,包括transform属性。

    注意:在this answer 上,您可以找到一种解决方法,将patch 转换为path,然后再转换为PathCollection,与单独的补丁绘制相比,绘制效率更高。

    【讨论】:

      猜你喜欢
      • 2010-12-17
      • 2020-02-11
      • 2013-07-04
      • 2013-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多