Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
568 views
in Technique[技术] by (71.8m points)

matplotlib change a Patch in PatchCollection

PatchCollection accepts a list of Patches and allows me to transform / add them to a canvas all at once. But changes to the one of the Patches after the construction of the PatchCollection object are not reflected

for example:

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)

I'm looking for a matplotlib collection that will group patches just so I can transform them together, but I want to be able to change the individual patches as well.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I don't know of a collection which will do what you want, but you could write one for yourself fairly easily:

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...