SHARE
TWEET

SimpleAnimatedPlot

paulnakroshis Mar 21st, 2012 797 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #
  2. """
  3. This short code snippet utilizes the new animation package in matplotlib 1.1.0
  4. It's the shortest snippet that I know of that can produce an animate plot in
  5. python. I'm hoping that the animation package can be improved so that one could
  6. more simply animate things. What do you think?
  7. """
  8. import numpy as np
  9. import matplotlib.pyplot as plt
  10. import matplotlib.animation as animation
  11.  
  12.  
  13. def simData():
  14. # this function is called as the argument for
  15. # the simPoints function. This function contains
  16. # (or defines) and iterator---a device that computes
  17. # a value, passes it back to the main program, and then
  18. # returns to exactly where it left off in the function.
  19. # I believe that one has to use this method to animate a plot
  20. # using the matplotlib animation package.
  21.     t_max = 10.0
  22.     dt = 0.05
  23.     x = 0.0
  24.     t = 0.0
  25.     while t < t_max:
  26.         x = np.sin(np.pi*t)
  27.         t = t + dt
  28.         yield x, t
  29.  
  30. def simPoints(simData):
  31.     x, t = simData[0], simData[1]
  32.     time_text.set_text(time_template%(t))
  33.     line.set_data(t, x)
  34.     return line, time_text
  35.  
  36.  
  37. ##
  38. ##   set up figure for plotting:
  39. ##
  40. fig = plt.figure()
  41. ax = fig.add_subplot(111)
  42. line, = ax.plot([], [], 'bo', ms=10) # I'm still not clear on this stucture...
  43. ax.set_ylim(-1, 1)
  44. ax.set_xlim(0, 10)
  45. ##
  46. time_template = 'Time = %.1f s'    # prints running simulation time
  47. time_text = ax.text(0.05, 0.9, '', transform=ax.transAxes)
  48. ## Now call the animation package:
  49. ani = animation.FuncAnimation(fig, simPoints, simData, blit=False, interval=10,
  50.     repeat=True)
  51. plt.show()
RAW Paste Data
Want to get better at Python?
Learn to code Python in 2017
Top