绘制 y=omega*x^2 的动画,其中 omega 从 -3 到 3 变化

问题描述 投票:0回答:1

我想绘制 y = omega*x^2 ,其中 omega 从 -3 到 3 变化,步长为 0.25(x 跨越 -4 到 4,步长为 0.001)。我的代码的当前版本(如下)仅使 omega 从 0 开始,而不是从 -3 开始。如何调整我的代码以使 omega 在我想要的范围内变化?

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

fig = plt.figure()
axis = plt.axes(xlim=(-4, 4), ylim=(-40, 40))
line, = axis.plot([], [], lw=3)

def init():
    line.set_data([], [])
    return line,

def animate(omega):
    x = np.linspace(-4, 4, 8000)
    y = omega*x**2
    line.set_data(x, y)
    return line,

anim = FuncAnimation(fig, animate, init_func=init, frames=500, interval=100, blit=True)

plt.show()

这就是我想要的结果:

https://i.sstatic.net/Ar2PX.gif

python matplotlib animation matplotlib-animation
1个回答
0
投票

animate 函数的参数是帧编号,从 0 开始。您可以做的是创建一个

omega
值数组,并使用帧编号对该数组进行索引。

def animate(i):
    y = omega[i]*x**2
    line.set_data(x, y)
    return line,

x = np.arange(-4, 4+0.001, 0.001)
domega = 0.25
omega = np.arange(-3, 3+domega, domega)

anim = FuncAnimation(fig, animate, init_func=init, frames=omega.size, interval=100, blit=True)

结果:

© www.soinside.com 2019 - 2024. All rights reserved.