当 omega 从 -3 开始到 3 时绘制 y=omega*x^2 的 Python 动画

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

在Python中,我想绘制y=omega*x^2,其中omega从-3变为3,步长为0.25,x从-4变为4,步长为0.001。但是这段代码给我的曲线是从 0 开始的 omega。我希望当 omega 从 -3 开始到 3 时曲线正在移动,就像这样。

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

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

如何解决?

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.