数据浏览器

在多个画布之间连接数据。

此示例介绍了如何与多个画布交互数据。这样,您可以选择并突出显示一个轴上的点,并在另一个轴上生成该点的数据。

数据浏览器示例

  1. import numpy as np
  2. class PointBrowser(object):
  3. """
  4. Click on a point to select and highlight it -- the data that
  5. generated the point will be shown in the lower axes. Use the 'n'
  6. and 'p' keys to browse through the next and previous points
  7. """
  8. def __init__(self):
  9. self.lastind = 0
  10. self.text = ax.text(0.05, 0.95, 'selected: none',
  11. transform=ax.transAxes, va='top')
  12. self.selected, = ax.plot([xs[0]], [ys[0]], 'o', ms=12, alpha=0.4,
  13. color='yellow', visible=False)
  14. def onpress(self, event):
  15. if self.lastind is None:
  16. return
  17. if event.key not in ('n', 'p'):
  18. return
  19. if event.key == 'n':
  20. inc = 1
  21. else:
  22. inc = -1
  23. self.lastind += inc
  24. self.lastind = np.clip(self.lastind, 0, len(xs) - 1)
  25. self.update()
  26. def onpick(self, event):
  27. if event.artist != line:
  28. return True
  29. N = len(event.ind)
  30. if not N:
  31. return True
  32. # the click locations
  33. x = event.mouseevent.xdata
  34. y = event.mouseevent.ydata
  35. distances = np.hypot(x - xs[event.ind], y - ys[event.ind])
  36. indmin = distances.argmin()
  37. dataind = event.ind[indmin]
  38. self.lastind = dataind
  39. self.update()
  40. def update(self):
  41. if self.lastind is None:
  42. return
  43. dataind = self.lastind
  44. ax2.cla()
  45. ax2.plot(X[dataind])
  46. ax2.text(0.05, 0.9, 'mu=%1.3f\nsigma=%1.3f' % (xs[dataind], ys[dataind]),
  47. transform=ax2.transAxes, va='top')
  48. ax2.set_ylim(-0.5, 1.5)
  49. self.selected.set_visible(True)
  50. self.selected.set_data(xs[dataind], ys[dataind])
  51. self.text.set_text('selected: %d' % dataind)
  52. fig.canvas.draw()
  53. if __name__ == '__main__':
  54. import matplotlib.pyplot as plt
  55. # Fixing random state for reproducibility
  56. np.random.seed(19680801)
  57. X = np.random.rand(100, 200)
  58. xs = np.mean(X, axis=1)
  59. ys = np.std(X, axis=1)
  60. fig, (ax, ax2) = plt.subplots(2, 1)
  61. ax.set_title('click on point to plot time series')
  62. line, = ax.plot(xs, ys, 'o', picker=5) # 5 points tolerance
  63. browser = PointBrowser()
  64. fig.canvas.mpl_connect('pick_event', browser.onpick)
  65. fig.canvas.mpl_connect('key_press_event', browser.onpress)
  66. plt.show()

下载这个示例