matplotlib集合升级

2024-10-03 15:27:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我想更新补丁集。我查看了在matplotlib change a Patch in PatchCollection给出的解决方案,并试图根据我的需要进行修改。它工作得很好,没有错误,但它只是改变了最后一个矩形的位置。我要它更新所有新的矩形位置。在

import matplotlib.collections as mcollections
import matplotlib as mpl
import matplotlib.pyplot as plt

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

m=[]
for i in range(5):
    print(i)
    rect = mpl.patches.Rectangle((i,2),1,1)
    m.append(rect)
    rect = mpl.patches.Rectangle((i,3),1,1)
    m.append(rect)

# This is just for display purpose and will be commented out        
collection = mcollections.PatchCollection(m)
ax = plt.figure(None).gca()
ax.set_xlim(0,10)
ax.set_ylim(0,10)
ax.add_artist(collection)
plt.show()

j = []
for i in range(10):
    rect.set_xy((i,5))
    rect.set_height(2)
    rect.set_width(2)
    j.append(rect)
    print(i)   

print(len(j))
m[:] = j[:]   

collection = UpdatablePatchCollection(m)
ax = plt.figure(None).gca()
ax.set_xlim(0,10)
ax.set_ylim(0,10)
ax.add_artist(collection)
plt.show()

结果是第一次表演():enter image description here

第二个表演()是:enter image description here 第二个循环只替换最后一个值。在

这有点像我之前的问题。如果这行得通,我也会接受答案。谢谢


Tags: inrectimportselfmatplotlibaspltax