dynamic_image.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. """
  2. =================================================
  3. Animated image using a precomputed list of images
  4. =================================================
  5. """
  6. import numpy as np
  7. import matplotlib.pyplot as plt
  8. import matplotlib.animation as animation
  9. fig, ax = plt.subplots()
  10. def f(x, y):
  11. return np.sin(x) + np.cos(y)
  12. x = np.linspace(0, 2 * np.pi, 120)
  13. y = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1)
  14. # ims is a list of lists, each row is a list of artists to draw in the
  15. # current frame; here we are just animating one artist, the image, in
  16. # each frame
  17. ims = []
  18. for i in range(60):
  19. x += np.pi / 15.
  20. y += np.pi / 20.
  21. im = ax.imshow(f(x, y), animated=True)
  22. if i == 0:
  23. ax.imshow(f(x, y)) # show an initial one first
  24. ims.append([im])
  25. ani = animation.ArtistAnimation(fig, ims, interval=50, blit=True,
  26. repeat_delay=1000)
  27. # To save the animation, use e.g.
  28. #
  29. # ani.save("movie.mp4")
  30. #
  31. # or
  32. #
  33. # writer = animation.FFMpegWriter(
  34. # fps=15, metadata=dict(artist='Me'), bitrate=1800)
  35. # ani.save("movie.mp4", writer=writer)
  36. plt.show()