Trifinder 事件演示

显示使用TriFinder对象的示例。当鼠标在三角测量上移动时,光标下方的三角形将突出显示,三角形的索引将显示在图表标题中。

Trifinder 事件演示

  1. import matplotlib.pyplot as plt
  2. from matplotlib.tri import Triangulation
  3. from matplotlib.patches import Polygon
  4. import numpy as np
  5. def update_polygon(tri):
  6. if tri == -1:
  7. points = [0, 0, 0]
  8. else:
  9. points = triang.triangles[tri]
  10. xs = triang.x[points]
  11. ys = triang.y[points]
  12. polygon.set_xy(np.column_stack([xs, ys]))
  13. def motion_notify(event):
  14. if event.inaxes is None:
  15. tri = -1
  16. else:
  17. tri = trifinder(event.xdata, event.ydata)
  18. update_polygon(tri)
  19. plt.title('In triangle %i' % tri)
  20. event.canvas.draw()
  21. # Create a Triangulation.
  22. n_angles = 16
  23. n_radii = 5
  24. min_radius = 0.25
  25. radii = np.linspace(min_radius, 0.95, n_radii)
  26. angles = np.linspace(0, 2 * np.pi, n_angles, endpoint=False)
  27. angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
  28. angles[:, 1::2] += np.pi / n_angles
  29. x = (radii*np.cos(angles)).flatten()
  30. y = (radii*np.sin(angles)).flatten()
  31. triang = Triangulation(x, y)
  32. triang.set_mask(np.hypot(x[triang.triangles].mean(axis=1),
  33. y[triang.triangles].mean(axis=1))
  34. < min_radius)
  35. # Use the triangulation's default TriFinder object.
  36. trifinder = triang.get_trifinder()
  37. # Setup plot and callbacks.
  38. plt.subplot(111, aspect='equal')
  39. plt.triplot(triang, 'bo-')
  40. polygon = Polygon([[0, 0], [0, 0]], facecolor='y') # dummy data for xs,ys
  41. update_polygon(-1)
  42. plt.gca().add_patch(polygon)
  43. plt.gcf().canvas.mpl_connect('motion_notify_event', motion_notify)
  44. plt.show()

下载这个示例