plt19_animation.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. # View more python tutorials on my Youtube and Youku channel!!!
  2. # Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
  3. # Youku video tutorial: http://i.youku.com/pythontutorial
  4. # 19 - animation
  5. """
  6. Please note, this script is for python3+.
  7. If you are using python2+, please modify it accordingly.
  8. Tutorial reference:
  9. http://matplotlib.org/examples/animation/simple_anim.html
  10. More animation example code:
  11. http://matplotlib.org/examples/animation/
  12. """
  13. import numpy as np
  14. from matplotlib import pyplot as plt
  15. from matplotlib import animation
  16. fig, ax = plt.subplots()
  17. x = np.arange(0, 2*np.pi, 0.01)
  18. line, = ax.plot(x, np.sin(x))
  19. def animate(i):
  20. line.set_ydata(np.sin(x + i/10.0)) # update the data
  21. return line,
  22. # Init only required for blitting to give a clean slate.
  23. def init():
  24. line.set_ydata(np.sin(x))
  25. return line,
  26. # call the animator. blit=True means only re-draw the parts that have changed.
  27. # blit=True dose not work on Mac, set blit=False
  28. # interval= update frequency
  29. ani = animation.FuncAnimation(fig=fig, func=animate, frames=100, init_func=init,
  30. interval=20, blit=False)
  31. # save the animation as an mp4. This requires ffmpeg or mencoder to be
  32. # installed. The extra_args ensure that the x264 codec is used, so that
  33. # the video can be embedded in html5. You may need to adjust this for
  34. # your system: for more information, see
  35. # http://matplotlib.sourceforge.net/api/animation_api.html
  36. # anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])
  37. plt.show()