{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Polygon editor\n\nThis is an example to show how to build cross-GUI applications using\nMatplotlib event handling to interact with objects on the canvas.\n\n<div class=\"alert alert-info\"><h4>Note</h4><p>This example exercises the interactive capabilities of Matplotlib, and this\n    will not appear in the static documentation. Please run this code on your\n    machine to see the interactivity.\n\n    You can copy and paste individual parts, or download the entire example\n    using the link at the bottom of the page.</p></div>\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import numpy as np\n\nfrom matplotlib.artist import Artist\nfrom matplotlib.lines import Line2D\n\n\ndef dist_point_to_segment(p, s0, s1):\n    \"\"\"\n    Get the distance from the point *p* to the segment (*s0*, *s1*), where\n    *p*, *s0*, *s1* are ``[x, y]`` arrays.\n    \"\"\"\n    s01 = s1 - s0\n    s0p = p - s0\n    if (s01 == 0).all():\n        return np.hypot(*s0p)\n    # Project onto segment, without going past segment ends.\n    p1 = s0 + np.clip((s0p @ s01) / (s01 @ s01), 0, 1) * s01\n    return np.hypot(*(p - p1))\n\n\nclass PolygonInteractor:\n    \"\"\"\n    A polygon editor.\n\n    Key-bindings\n\n      't' toggle vertex markers on and off.  When vertex markers are on,\n          you can move them, delete them\n\n      'd' delete the vertex under point\n\n      'i' insert a vertex at point.  You must be within epsilon of the\n          line connecting two existing vertices\n\n    \"\"\"\n\n    showverts = True\n    epsilon = 5  # max pixel distance to count as a vertex hit\n\n    def __init__(self, ax, poly):\n        if poly.figure is None:\n            raise RuntimeError('You must first add the polygon to a figure '\n                               'or canvas before defining the interactor')\n        self.ax = ax\n        canvas = poly.figure.canvas\n        self.poly = poly\n\n        x, y = zip(*self.poly.xy)\n        self.line = Line2D(x, y,\n                           marker='o', markerfacecolor='r',\n                           animated=True)\n        self.ax.add_line(self.line)\n\n        self.cid = self.poly.add_callback(self.poly_changed)\n        self._ind = None  # the active vert\n\n        canvas.mpl_connect('draw_event', self.on_draw)\n        canvas.mpl_connect('button_press_event', self.on_button_press)\n        canvas.mpl_connect('key_press_event', self.on_key_press)\n        canvas.mpl_connect('button_release_event', self.on_button_release)\n        canvas.mpl_connect('motion_notify_event', self.on_mouse_move)\n        self.canvas = canvas\n\n    def on_draw(self, event):\n        self.background = self.canvas.copy_from_bbox(self.ax.bbox)\n        self.ax.draw_artist(self.poly)\n        self.ax.draw_artist(self.line)\n        # do not need to blit here, this will fire before the screen is\n        # updated\n\n    def poly_changed(self, poly):\n        \"\"\"This method is called whenever the pathpatch object is called.\"\"\"\n        # only copy the artist props to the line (except visibility)\n        vis = self.line.get_visible()\n        Artist.update_from(self.line, poly)\n        self.line.set_visible(vis)  # don't use the poly visibility state\n\n    def get_ind_under_point(self, event):\n        \"\"\"\n        Return the index of the point closest to the event position or *None*\n        if no point is within ``self.epsilon`` to the event position.\n        \"\"\"\n        # display coords\n        xy = np.asarray(self.poly.xy)\n        xyt = self.poly.get_transform().transform(xy)\n        xt, yt = xyt[:, 0], xyt[:, 1]\n        d = np.hypot(xt - event.x, yt - event.y)\n        indseq, = np.nonzero(d == d.min())\n        ind = indseq[0]\n\n        if d[ind] >= self.epsilon:\n            ind = None\n\n        return ind\n\n    def on_button_press(self, event):\n        \"\"\"Callback for mouse button presses.\"\"\"\n        if not self.showverts:\n            return\n        if event.inaxes is None:\n            return\n        if event.button != 1:\n            return\n        self._ind = self.get_ind_under_point(event)\n\n    def on_button_release(self, event):\n        \"\"\"Callback for mouse button releases.\"\"\"\n        if not self.showverts:\n            return\n        if event.button != 1:\n            return\n        self._ind = None\n\n    def on_key_press(self, event):\n        \"\"\"Callback for key presses.\"\"\"\n        if not event.inaxes:\n            return\n        if event.key == 't':\n            self.showverts = not self.showverts\n            self.line.set_visible(self.showverts)\n            if not self.showverts:\n                self._ind = None\n        elif event.key == 'd':\n            ind = self.get_ind_under_point(event)\n            if ind is not None:\n                self.poly.xy = np.delete(self.poly.xy,\n                                         ind, axis=0)\n                self.line.set_data(zip(*self.poly.xy))\n        elif event.key == 'i':\n            xys = self.poly.get_transform().transform(self.poly.xy)\n            p = event.x, event.y  # display coords\n            for i in range(len(xys) - 1):\n                s0 = xys[i]\n                s1 = xys[i + 1]\n                d = dist_point_to_segment(p, s0, s1)\n                if d <= self.epsilon:\n                    self.poly.xy = np.insert(\n                        self.poly.xy, i+1,\n                        [event.xdata, event.ydata],\n                        axis=0)\n                    self.line.set_data(zip(*self.poly.xy))\n                    break\n        if self.line.stale:\n            self.canvas.draw_idle()\n\n    def on_mouse_move(self, event):\n        \"\"\"Callback for mouse movements.\"\"\"\n        if not self.showverts:\n            return\n        if self._ind is None:\n            return\n        if event.inaxes is None:\n            return\n        if event.button != 1:\n            return\n        x, y = event.xdata, event.ydata\n\n        self.poly.xy[self._ind] = x, y\n        if self._ind == 0:\n            self.poly.xy[-1] = x, y\n        elif self._ind == len(self.poly.xy) - 1:\n            self.poly.xy[0] = x, y\n        self.line.set_data(zip(*self.poly.xy))\n\n        self.canvas.restore_region(self.background)\n        self.ax.draw_artist(self.poly)\n        self.ax.draw_artist(self.line)\n        self.canvas.blit(self.ax.bbox)\n\n\nif __name__ == '__main__':\n    import matplotlib.pyplot as plt\n\n    from matplotlib.patches import Polygon\n\n    theta = np.arange(0, 2*np.pi, 0.1)\n    r = 1.5\n\n    xs = r * np.cos(theta)\n    ys = r * np.sin(theta)\n\n    poly = Polygon(np.column_stack([xs, ys]), animated=True)\n\n    fig, ax = plt.subplots()\n    ax.add_patch(poly)\n    p = PolygonInteractor(ax, poly)\n\n    ax.set_title('Click and drag a point to move it')\n    ax.set_xlim(-2, 2)\n    ax.set_ylim(-2, 2)\n    plt.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.14.6"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}