使用FuncAnimation对函数参数随时间变化的函数进行动画处理

时间:2018-11-30 00:18:32

标签: python matplotlib plot

我正在尝试对一维函数进行动画处理,其中函数输入相同,但函数参数随时间变化。我要设置动画的功能是

f(x)= sin(a * pi * x)/(b * x)+(x-1)^ 4

这里要绘制的数据是相同的,但是a,b每次更新都在变化。我正在使用python和matplotlib库。我最初的尝试如下:

fig,ax = plt.subplots()
line, = ax.plot([],[])

def animate(i,func_params):
    x = np.linspace(-0.5,2.5,num = 200)
    a=func_params[i][0]
    b=func_params[i][1]
    y=np.sin(a*math.pi*x)/b*x + (x-1)**4
    line.set_xdata(x)
    line.set_ydata(y)
    return line,

ani = animation.FuncAnimation(fig,animate,frames=len(visualize_pop),fargs=(visualize_func,),interval = 100,blit=True)
plt.show()

上面的代码没有绘制任何内容。

编辑:基于注释更新了代码。

1 个答案:

答案 0 :(得分:0)

您的问题是使用plot([],[])时,您没有给matplotlib数据,因此无法确定轴的极限。因此,它使用一些默认值,这些默认值超出了您实际要绘制的数据范围。因此,您有两种选择:

1)将限制设置为一些值,其中将包含所有情况下的所有绘制数据, 例如

ax.set_xlim([-0.5,2.5])
ax.set_ylim([-2,6])

2)让ax每帧自动计算极限,并在动画函数中使用这两个命令来重新缩放图see here(请注意,只有关闭blitting后,此选项才能正常工作) :

ax.relim()
ax.autoscale_view()

这里仍然是您的代码的完整版本(解决方案(1)的命令已注释掉,我更改了一些表示法):

from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np

fig,ax = plt.subplots()
x = np.linspace(-0.5,2.5,num = 200)
line, = ax.plot([],[])

#ax.set_xlim([-0.5,2.5])
#ax.set_ylim([-2,6])

##assuming some parameters, because none were given by the OP:
N = 20
func_args = np.array([np.linspace(1,2,N), np.linspace(2,1,N)])

def animate(i,func_params):
    a=func_params[0,i]
    b=func_params[1,i]
    y=np.sin(a*np.pi*x)/b*x + (x-1)**4
    line.set_xdata(x)
    line.set_ydata(y)
    ax.relim()
    ax.autoscale_view()
    return line, ax

##blit=True will not update the axes labels correctly
ani = FuncAnimation(
    fig,animate,frames=N, fargs=(func_args,),interval = 100 #, blit=True
)
plt.show()
相关问题