matplotlib在PatchCollection中更改Patch

时间:2012-06-05 19:21:55

标签: matplotlib

PatchCollection接受Patch es的列表,并允许我一次性转换/添加到画布。但是,Patch对象构造后对PatchCollection es之一的更改未得到反映

例如:

import matplotlib.pyplot as plt
import matplotlib as mpl

rect = mpl.patches.Rectangle((0,0),1,1)

rect.set_xy((1,1))
collection = mpl.collections.PatchCollection([rect])
rect.set_xy((2,2))

ax = plt.figure(None).gca()
ax.set_xlim(0,5)
ax.set_ylim(0,5)
ax.add_artist(collection)
plt.show()  #shows a rectangle at (1,1), not (2,2)

我正在寻找一个matplotlib集合,它将对补丁进行分组,以便我可以将它们一起转换,但我希望能够更改单个补丁。

1 个答案:

答案 0 :(得分:2)

我不知道哪个系列会做你想要的,但你可以很容易地为自己写一个:

import matplotlib.collections as mcollections

import matplotlib.pyplot as plt
import matplotlib as mpl


class UpdatablePatchCollection(mcollections.PatchCollection):
    def __init__(self, patches, *args, **kwargs):
        self.patches = patches
        mcollections.PatchCollection.__init__(self, patches, *args, **kwargs)

    def get_paths(self):
        self.set_paths(self.patches)
        return self._paths


rect = mpl.patches.Rectangle((0,0),1,1)

rect.set_xy((1,1))
collection = UpdatablePatchCollection([rect])
rect.set_xy((2,2))

ax = plt.figure(None).gca()
ax.set_xlim(0,5)
ax.set_ylim(0,5)
ax.add_artist(collection)
plt.show()  # now shows a rectangle at (2,2)