示波器

模拟示波器。

示波器示例

  1. import numpy as np
  2. from matplotlib.lines import Line2D
  3. import matplotlib.pyplot as plt
  4. import matplotlib.animation as animation
  5. class Scope(object):
  6. def __init__(self, ax, maxt=2, dt=0.02):
  7. self.ax = ax
  8. self.dt = dt
  9. self.maxt = maxt
  10. self.tdata = [0]
  11. self.ydata = [0]
  12. self.line = Line2D(self.tdata, self.ydata)
  13. self.ax.add_line(self.line)
  14. self.ax.set_ylim(-.1, 1.1)
  15. self.ax.set_xlim(0, self.maxt)
  16. def update(self, y):
  17. lastt = self.tdata[-1]
  18. if lastt > self.tdata[0] + self.maxt: # reset the arrays
  19. self.tdata = [self.tdata[-1]]
  20. self.ydata = [self.ydata[-1]]
  21. self.ax.set_xlim(self.tdata[0], self.tdata[0] + self.maxt)
  22. self.ax.figure.canvas.draw()
  23. t = self.tdata[-1] + self.dt
  24. self.tdata.append(t)
  25. self.ydata.append(y)
  26. self.line.set_data(self.tdata, self.ydata)
  27. return self.line,
  28. def emitter(p=0.03):
  29. 'return a random value with probability p, else 0'
  30. while True:
  31. v = np.random.rand(1)
  32. if v > p:
  33. yield 0.
  34. else:
  35. yield np.random.rand(1)
  36. # Fixing random state for reproducibility
  37. np.random.seed(19680801)
  38. fig, ax = plt.subplots()
  39. scope = Scope(ax)
  40. # pass a generator in "emitter" to produce data for the update func
  41. ani = animation.FuncAnimation(fig, scope.update, emitter, interval=10,
  42. blit=True)
  43. plt.show()

下载这个示例