从外部函数调用时如何使用matplotlib.animation

时间:2019-07-10 17:13:58

标签: python-3.x animation pde

我正在使用有限差分法求解方程,并希望为解决方案添加动画效果。设置表单的动画时:

import numpy as np
import matplotlib.animation as animation

dx = 0.1
x = np.linspace(0, 10, dx)
def time_step(p, dt, dx):
    return p + dt*f(p, dx)

def f(p, dx):
    ... #some spatial discretisation function 
    return p_updated

fig, ax = plt.subplots()
line, = ax.plot(x, p)

def update(i):
    global p, dt, dx
    p = time_step(p, dt dx)
    return line, 

ani = animation.FuncAnimation(fig, update, frames=np.arange(0, 10000, 1), blit=False, interval= 10, repeat = False)
plt.show()

然后它可以工作并正确显示动画。但是,我需要能够从单独的文件中调用该函数,然后它不再起作用。即:

import numpy as np
import matplotlib.animation as animation
from file1 import time_step

def anim(p, D, dt, dx, animate_now, x):
    if animate_now:
        fig = plt.figure(figsize=(15,9))
        ax = fig.add_subplot(111)

        line, = ax.plot(x, p)

        def animate(i):
            global p
            p = time_step(p, dt, D, dx)
            line.set_ydata(p)
            return line,

        ani = animation.FuncAnimation(fig, animate, np.arange(1, 200),
            interval=50)

        plt.show()
    return ani

并从另一个文件调用函数anim,则错误消息就是“ UnboundLocalError:分配前引用的本地变量'p'”。如何纠正代码以使其正常工作?

0 个答案:

没有答案