衰变

这个例子展示了:

  • 使用生成器来驱动动画,
  • 在动画期间更改轴限制。

衰变示例

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. import matplotlib.animation as animation
  4. def data_gen(t=0):
  5. cnt = 0
  6. while cnt < 1000:
  7. cnt += 1
  8. t += 0.1
  9. yield t, np.sin(2*np.pi*t) * np.exp(-t/10.)
  10. def init():
  11. ax.set_ylim(-1.1, 1.1)
  12. ax.set_xlim(0, 10)
  13. del xdata[:]
  14. del ydata[:]
  15. line.set_data(xdata, ydata)
  16. return line,
  17. fig, ax = plt.subplots()
  18. line, = ax.plot([], [], lw=2)
  19. ax.grid()
  20. xdata, ydata = [], []
  21. def run(data):
  22. # update the data
  23. t, y = data
  24. xdata.append(t)
  25. ydata.append(y)
  26. xmin, xmax = ax.get_xlim()
  27. if t >= xmax:
  28. ax.set_xlim(xmin, 2*xmax)
  29. ax.figure.canvas.draw()
  30. line.set_data(xdata, ydata)
  31. return line,
  32. ani = animation.FuncAnimation(fig, run, data_gen, blit=False, interval=10,
  33. repeat=False, init_func=init)
  34. plt.show()

下载这个示例