{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Trifinder Event Demo\n\nExample showing the use of a TriFinder object. As the mouse is moved over the\ntriangulation, the triangle under the cursor is highlighted and the index of\nthe triangle is displayed in the plot title.\n\n

Note

\n\nThis example exercises the interactive capabilities of Matplotlib, and this\nwill not appear in the static documentation. Please run this code on your\nmachine to see the interactivity.\n\nYou can copy and paste individual parts, or download the entire example\nusing the link at the bottom of the page.\n\n
\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\nimport numpy as np\n\nfrom matplotlib.patches import Polygon\nfrom matplotlib.tri import Triangulation\n\n\ndef update_polygon(tri):\n if tri == -1:\n points = [0, 0, 0]\n else:\n points = triang.triangles[tri]\n xs = triang.x[points]\n ys = triang.y[points]\n polygon.set_xy(np.column_stack([xs, ys]))\n\n\ndef on_mouse_move(event):\n if event.inaxes is None:\n tri = -1\n else:\n tri = trifinder(event.xdata, event.ydata)\n update_polygon(tri)\n ax.set_title(f'In triangle {tri}')\n event.canvas.draw()\n\n\n# Create a Triangulation.\nn_angles = 16\nn_radii = 5\nmin_radius = 0.25\nradii = np.linspace(min_radius, 0.95, n_radii)\nangles = np.linspace(0, 2 * np.pi, n_angles, endpoint=False)\nangles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)\nangles[:, 1::2] += np.pi / n_angles\nx = (radii*np.cos(angles)).flatten()\ny = (radii*np.sin(angles)).flatten()\ntriang = Triangulation(x, y)\ntriang.set_mask(np.hypot(x[triang.triangles].mean(axis=1),\n y[triang.triangles].mean(axis=1))\n < min_radius)\n\n# Use the triangulation's default TriFinder object.\ntrifinder = triang.get_trifinder()\n\n# Setup plot and callbacks.\nfig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})\nax.triplot(triang, 'bo-')\npolygon = Polygon([[0, 0], [0, 0]], facecolor='y') # dummy data for (xs, ys)\nupdate_polygon(-1)\nax.add_patch(polygon)\nfig.canvas.mpl_connect('motion_notify_event', on_mouse_move)\nplt.show()" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.15" } }, "nbformat": 4, "nbformat_minor": 0 }