python+matplotlib實現滑鼠移動三角形高亮及索引顯示,pythonmatplotlib
Trifinder事件執行個體
執行個體展示Trifinder對象對的使用。當滑鼠移動到一個被分割的三角形上,這個三角形高亮顯示,並且它的標籤在表徵圖題顯示。
展示下示範結果:
完整代碼:
import matplotlib.pyplot as pltfrom matplotlib.tri import Triangulationfrom matplotlib.patches import Polygonimport numpy as npdef update_polygon(tri): if tri == -1: points = [0, 0, 0] else: points = triang.triangles[tri] xs = triang.x[points] ys = triang.y[points] polygon.set_xy(list(zip(xs, ys)))def motion_notify(event): if event.inaxes is None: tri = -1 else: tri = trifinder(event.xdata, event.ydata) update_polygon(tri) plt.title('In triangle %i' % tri) event.canvas.draw()# Create a Triangulation.n_angles = 16n_radii = 5min_radius = 0.25radii = np.linspace(min_radius, 0.95, n_radii)angles = np.linspace(0, 2 * np.pi, n_angles, endpoint=False)angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)angles[:, 1::2] += np.pi / n_anglesx = (radii*np.cos(angles)).flatten()y = (radii*np.sin(angles)).flatten()triang = Triangulation(x, y)triang.set_mask(np.hypot(x[triang.triangles].mean(axis=1), y[triang.triangles].mean(axis=1)) < min_radius)# Use the triangulation's default TriFinder object.trifinder = triang.get_trifinder()# Setup plot and callbacks.plt.subplot(111, aspect='equal')plt.triplot(triang, 'bo-')polygon = Polygon([[0, 0], [0, 0]], facecolor='y') # dummy data for xs,ysupdate_polygon(-1)plt.gca().add_patch(polygon)plt.gcf().canvas.mpl_connect('motion_notify_event', motion_notify)plt.show()
總結
本文所示是一個Python+matplotlib實現的簡單一實例,希望對大家有所協助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支援!