使用FuncAnimation设置函数参数随时间变化的函数的动画

2024-04-28 23:08:21 发布

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

我正在尝试制作一个一维函数的动画,其中的函数输入是相同的,但函数参数是随时间变化的。我尝试设置动画的功能是

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

这里要绘制的数据是相同的,但是a,b随着每次更新而改变。我的初步尝试如下:

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()

上面的代码没有绘制任何东西。你知道吗

编辑:根据注释更新代码。你知道吗


Tags: 函数nplinepifig绘制动画plt
1条回答
网友
1楼 · 发布于 2024-04-28 23:08:21

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

1)将限制设置为包含所有情况下所有打印数据的某些值, e、 g

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()

相关问题 更多 >