【问题标题】:Matplotlib FuncAnimation slowMatplotlib FuncAnimation 慢
【发布时间】:2013-11-16 08:38:46
【问题描述】:

我使用 matplotlib 的 FuncAnimation 创建了一个表面绑定过程的简单动画。然而,结果非常缓慢。我怀疑这是因为我正在重绘每一帧的所有元素,但我还没有找到解决方法。任何帮助表示赞赏。

import matplotlib
matplotlib.use('TKAgg')      # import proper graphics back-end for Mac OS X


import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
from matplotlib.collections import PatchCollection
from random import *

nx = 20     # x size of lattice
ny = 20     # y size of lattice

pAds = 0.01     # adsorption probability per time step
pDes = 0.0075   # desorption probability per time step

tMax = 500     # number of time steps

surface = np.zeros((nx,ny))              # create surface
xc = [0]
yc = [0]


# initialization and time step of simulation

def init():
    # initialize an empty list of circles
    patches = []            # empty array to hold drawable objects
    for x in range(0,nx):
        for y in range(0,ny):
            if(surface[x][y] == 0):
                patches.append(ax_surf.add_patch(plt.Circle((x+0.5,y+0.5),0.45,color='w')))
    lines, = ax_covr.plot([],[])
    patches.append(lines)
    return patches

def animate(i): 
    patches = []            # empty array of circles to be drawn
    for x in range(0,nx):
        for y in range(0,ny):
            if(surface[x][y] == 0):
                if(random() < pAds):
                    surface[x][y] = 1
                    patches.append(ax_surf.add_patch(plt.Circle((x+0.5,y+0.5),0.45,color='b')))
                else:
                    patches.append(ax_surf.add_patch(plt.Circle((x+0.5,y+0.5),0.45,color='w')))
            else:
                if(random()<pDes):
                    surface[x][y] = 0
                    patches.append(ax_surf.add_patch(plt.Circle((x+0.5,y+0.5),0.45,color='w')))
                else:
                    patches.append(ax_surf.add_patch(plt.Circle((x+0.5,y+0.5),0.45,color='b')))
    coverage = np.sum(surface)/(nx*ny)
    xc.append(i)
    yc.append(coverage)
    lines, = ax_covr.plot(xc,yc,'ro',ms=2,lw=0)
    patches.append(lines)
    return patches

# set up figure and animate


fig = plt.figure()
ax_surf = plt.subplot2grid((1, 2), (0, 0))
ax_covr = plt.subplot2grid((1, 2), (0, 1))
ax_surf.set_xlim(0,nx)
ax_surf.set_ylim(0,ny)
ax_covr.set_xlim(0,tMax)
ax_covr.set_ylim(0,1)

ax_surf.set_aspect(1)
ax_surf.axis('off')

ax_covr.set_aspect(tMax)

ax_surf.hold(False)

anim = animation.FuncAnimation(fig, animate, init_func=init, frames=tMax, interval=0, blit=True,repeat=False)
plt.show()

【问题讨论】:

    标签: python animation matplotlib


    【解决方案1】:

    使用之前的init / animate 调用的patches,而不是每次都创建一个新的。

    以下是修改后的代码。

    patches = []
    
    def init():
        global patches
        if patches:
            # prevent the second call of the init()
            return patches
        # initialize an empty list of circles
        for x in range(nx):
            for y in range(ny):
                if(surface[x][y] == 0):
                    patches.append(ax_surf.add_patch(plt.Circle((x+0.5,y+0.5),0.45,color='w')))
        lines, = ax_covr.plot([],[])
        patches.append(lines)
        return patches
    
    def animate(i): 
        global patches
        idx = 0
        for x in range(nx):
            for y in range(ny):
                if surface[x][y] == 0:
                    if random() < pAds:
                        surface[x][y] = 1
                        patches[idx] = ax_surf.add_patch(plt.Circle((x+0.5,y+0.5),0.45,color='b'))
                else:
                    if(random()<pDes):
                        surface[x][y] = 0
                        patches[idx] = ax_surf.add_patch(plt.Circle((x+0.5,y+0.5),0.45,color='w'))
                idx += 1
        coverage = np.sum(surface)/(nx*ny)
        xc.append(i)
        yc.append(coverage)
        lines, = ax_covr.plot(xc,yc,'ro',ms=2,lw=0)
        patches[idx] = lines
        return patches
    

    注意:使用全局变量来最小化修改。

    【讨论】:

    • 上述版本有时会在尝试访问不存在的数组条目时崩溃。我创建了一个强大的版本,它基本上为 nx*ny 圈子保留了足够的空间来适应使用:del patches[nx*ny:] 在每一帧之后安全地修剪数组。
    • @user2992602,崩溃怎么办?您是否收到任何错误消息或回溯?我刚刚更换了initanimate,跑了大约7次,没有崩溃。
    • 对不起 falsetru,但在 Win 7 上我无法重现崩溃(数组元素越界),我现在意识到只发生在我的 Mac OS X 上。感谢您的帮助。
    • @BeMuSeD,似乎init 函数在 OSX 中被调用了两次。如果已经初始化了全局变量patched,我修改了init函数提前返回。查看修改后的版本。
    猜你喜欢
    • 2013-11-19
    • 1970-01-01
    • 1970-01-01
    • 2018-08-14
    • 2014-01-08
    • 2015-01-09
    • 2013-09-15
    • 1970-01-01
    相关资源
    最近更新 更多