Skip to content

Instantly share code, notes, and snippets.

@parulnith
Last active August 17, 2022 07:36
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save parulnith/5d82f66f38704e09456fbc33ed5b67ae to your computer and use it in GitHub Desktop.
Save parulnith/5d82f66f38704e09456fbc33ed5b67ae to your computer and use it in GitHub Desktop.
Using matplotlib's FuncAnimation to do a basic animation of a sine wave moving across the screen:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation
plt.style.use('seaborn-pastel')
fig = plt.figure()
ax = plt.axes(xlim=(0, 4), ylim=(-2, 2))
line, = ax.plot([], [], lw=3)
def init():
line.set_data([], [])
return line,
def animate(i):
x = np.linspace(0, 4, 1000)
y = np.sin(2 * np.pi * (x - 0.01 * i))
line.set_data(x, y)
return line,
anim = FuncAnimation(fig, animate, init_func=init,
frames=200, interval=20, blit=True)
anim.save('sine_wave.gif', writer='imagemagick')
@anandprabhakar0507
Copy link

Nice..

@austindelatorre
Copy link

when I run this code I am getting "TypeError: 'MovieWriterRegistry' object is not an iterator". How do I fix this?

@alexitkes
Copy link

Hello.

Is it possible to show the animation just in the notebook without saving it to file? If I remove the anim.save line I just get an empty figure.

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment