Matplotlib:如何在PatchCollection中更改Patch

3
PatchCollection 接受一个Patch列表,并允许我一次性将它们转换/添加到画布中。但是,在构建PatchCollection对象后对其中一个Patch进行更改不会反映在画布上。
例如:
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个回答

3

我不知道有哪个集合可以满足你的需求,但是你可以很容易地为自己编写一个:

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)

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