代码之家  ›  专栏  ›  技术社区  ›  Ongky Denny Wijaya

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

  •  0
  • Ongky Denny Wijaya  · 技术社区  · 7 月前

    我想绘制y=ω*x^2,ω从-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

    1 回复  |  直到 7 月前
        1
  •  1
  •   jared    7 月前

    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)
    

    后果