pythonmatplotlibanimationmatplotlib-animation

Animation for plotting y=omega*x^2 with omega varying from -3 to 3


I want to plot y = omega*x^2 with omega varying from -3 to 3 with a step size of 0.25 (and x spanning -4 to 4 with a step size of 0.001). The current version of my code (below) only has omega start at 0 and not -3. How do I adjust my code to get omega to vary over the range I want?

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

This is my desired result:

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


Solution

  • The argument to the animate function is the frame number, which starts at 0. What you can do is create an array of omega values and index that array using the frame number.

    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)
    

    Result: