Python Matplotlib:PatchCollection动画不升级

2024-06-16 11:28:35 发布

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

我一直在尝试优化我的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()

动画永远不会更新。它被冻结在一块空地上。在

我愿意接受其他优化方法。当前的解决方案似乎相当冗长,只需在每帧中添加一个矩形。在


Tags: fromimportlenmatplotlib动画coordsaxpatch
1条回答
网友
1楼 · 发布于 2024-06-16 11:28:35

我不太清楚你的代码。把一个矩形的facecolor从白色切换到黑色就是在绘图中“添加”这个矩形吗?在

我花了一点时间才弄明白为什么你的代码不起作用,但结果证明这是一个愚蠢的错误。问题出在ax.add_patch(patch)行。实际上,在绘图上添加两组矩形,一组作为单个Rectangle实例,另一组作为PatchCollection的一部分。似乎Rectangles停留在集合的顶部,因此您没有看到动画。只需注释有问题的行(ax.add_patch(patch))就可以解决问题。在

{1s}你可能想看到更大的值。在

下面我将如何编写代码(loosely inspired by this question on SO):

Nx = 30
Ny = 20
size = 0.5

colors = ['w']*Nx*Ny

fig, ax = plt.subplots()

rects = []
for i in range(Nx):
    for j in range(Ny):
        rect = plt.Rectangle([i - size / 2, j - size / 2], size, size)
        rects.append(rect)

collection = PatchCollection(rects, animated=True)

ax.add_collection(collection)
ax.autoscale_view(True)

def init():
    # sets all the patches in the collection to white
    collection.set_facecolor(colors)
    return collection,

def animate(i):
    colors[i] = 'k'
    collection.set_facecolors(colors)
    return collection,

ani = FuncAnimation(fig, init_func=init, func=animate, frames=Nx*Ny,
        interval=1e2, blit=True)

enter image description here

相关问题 更多 >