我一直在尝试优化我的matplotlib动画,其中包括在每次迭代时向绘图中添加一个矩形。由于动画函数在每次迭代中都会更新整个面片集,因此对于较大的面片集,它的速度非常慢。在
根据一些消息来源,这个过程可以通过使用PatchCollection而不是在补丁上循环来加快。这是我的尝试:
from matplotlib import pyplot
from matplotlib import patches
from matplotlib import animation
from matplotlib.collections import PatchCollection
fig = pyplot.figure()
coords = [[1,0],[0,1],[0,0]] #arbitrary set of coordinates
ax = pyplot.axes(xlim=(0, len(coords)), ylim=(0, len(coords)))
ax.set_aspect('equal')
patchList = list()
for coord in coords:
patch = patches.Rectangle(coord, 1, 1, color="white")
ax.add_patch(patch)
patch.set_visible = True
patchList.append(patch)
rectangles = PatchCollection(patchList, animated=True)
ax.add_collection(rectangles)
black = []
white = ["white"]*len(patchList)
def animate(i):
black.append("black")
white.pop()
colors = black + white
print(colors)
rectangles.set_facecolors(colors)
print("%.2f%%..."%(100*float(i+1)/len(coords)))
return rectangles,
anim = animation.FuncAnimation(fig, animate,
# init_func=init,
frames=len(coords)-1,
interval=1,
blit=True,
repeat = False)
pyplot.show()
动画永远不会更新。它被冻结在一块空地上。在
我愿意接受其他优化方法。当前的解决方案似乎相当冗长,只需在每帧中添加一个矩形。在
我不太清楚你的代码。把一个矩形的
facecolor
从白色切换到黑色就是在绘图中“添加”这个矩形吗?在我花了一点时间才弄明白为什么你的代码不起作用,但结果证明这是一个愚蠢的错误。问题出在
ax.add_patch(patch)
行。实际上,在绘图上添加两组矩形,一组作为单个Rectangle
实例,另一组作为PatchCollection
的一部分。似乎Rectangles
停留在集合的顶部,因此您没有看到动画。只需注释有问题的行(ax.add_patch(patch)
)就可以解决问题。在{1s}你可能想看到更大的值。在
下面我将如何编写代码(loosely inspired by this question on SO):
相关问题 更多 >
编程相关推荐