重采样数据

下采样会降低信号的采样率或采样大小。在本教程中,当通过拖动和缩放调整打印时,将对信号进行缩减采样。

重采样数据示例

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. # A class that will downsample the data and recompute when zoomed.
  4. class DataDisplayDownsampler(object):
  5. def __init__(self, xdata, ydata):
  6. self.origYData = ydata
  7. self.origXData = xdata
  8. self.max_points = 50
  9. self.delta = xdata[-1] - xdata[0]
  10. def downsample(self, xstart, xend):
  11. # get the points in the view range
  12. mask = (self.origXData > xstart) & (self.origXData < xend)
  13. # dilate the mask by one to catch the points just outside
  14. # of the view range to not truncate the line
  15. mask = np.convolve([1, 1], mask, mode='same').astype(bool)
  16. # sort out how many points to drop
  17. ratio = max(np.sum(mask) // self.max_points, 1)
  18. # mask data
  19. xdata = self.origXData[mask]
  20. ydata = self.origYData[mask]
  21. # downsample data
  22. xdata = xdata[::ratio]
  23. ydata = ydata[::ratio]
  24. print("using {} of {} visible points".format(
  25. len(ydata), np.sum(mask)))
  26. return xdata, ydata
  27. def update(self, ax):
  28. # Update the line
  29. lims = ax.viewLim
  30. if np.abs(lims.width - self.delta) > 1e-8:
  31. self.delta = lims.width
  32. xstart, xend = lims.intervalx
  33. self.line.set_data(*self.downsample(xstart, xend))
  34. ax.figure.canvas.draw_idle()
  35. # Create a signal
  36. xdata = np.linspace(16, 365, (365-16)*4)
  37. ydata = np.sin(2*np.pi*xdata/153) + np.cos(2*np.pi*xdata/127)
  38. d = DataDisplayDownsampler(xdata, ydata)
  39. fig, ax = plt.subplots()
  40. # Hook up the line
  41. d.line, = ax.plot(xdata, ydata, 'o-')
  42. ax.set_autoscale_on(False) # Otherwise, infinite loop
  43. # Connect for changing the view limits
  44. ax.callbacks.connect('xlim_changed', d.update)
  45. ax.set_xlim(16, 365)
  46. plt.show()

下载这个示例