{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Select indices from a collection using polygon selector\n\nShows how one can select indices of a polygon interactively.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import numpy as np\n\nfrom matplotlib.path import Path\nfrom matplotlib.widgets import PolygonSelector\n\n\nclass SelectFromCollection:\n    \"\"\"\n    Select indices from a matplotlib collection using `PolygonSelector`.\n\n    Selected indices are saved in the `ind` attribute. This tool fades out the\n    points that are not part of the selection (i.e., reduces their alpha\n    values). If your collection has alpha < 1, this tool will permanently\n    alter the alpha values.\n\n    Note that this tool selects collection objects based on their *origins*\n    (i.e., `offsets`).\n\n    Parameters\n    ----------\n    ax : `~matplotlib.axes.Axes`\n        Axes to interact with.\n    collection : `matplotlib.collections.Collection` subclass\n        Collection you want to select from.\n    alpha_other : 0 <= float <= 1\n        To highlight a selection, this tool sets all selected points to an\n        alpha value of 1 and non-selected points to *alpha_other*.\n    \"\"\"\n\n    def __init__(self, ax, collection, alpha_other=0.3):\n        self.canvas = ax.figure.canvas\n        self.collection = collection\n        self.alpha_other = alpha_other\n\n        self.xys = collection.get_offsets()\n        self.Npts = len(self.xys)\n\n        # Ensure that we have separate colors for each object\n        self.fc = collection.get_facecolors()\n        if len(self.fc) == 0:\n            raise ValueError('Collection must have a facecolor')\n        elif len(self.fc) == 1:\n            self.fc = np.tile(self.fc, (self.Npts, 1))\n\n        self.poly = PolygonSelector(ax, self.onselect, draw_bounding_box=True)\n        self.ind = []\n\n    def onselect(self, verts):\n        path = Path(verts)\n        self.ind = np.nonzero(path.contains_points(self.xys))[0]\n        self.fc[:, -1] = self.alpha_other\n        self.fc[self.ind, -1] = 1\n        self.collection.set_facecolors(self.fc)\n        self.canvas.draw_idle()\n\n    def disconnect(self):\n        self.poly.disconnect_events()\n        self.fc[:, -1] = 1\n        self.collection.set_facecolors(self.fc)\n        self.canvas.draw_idle()\n\n\nif __name__ == '__main__':\n    import matplotlib.pyplot as plt\n\n    fig, ax = plt.subplots()\n    grid_size = 5\n    grid_x = np.tile(np.arange(grid_size), grid_size)\n    grid_y = np.repeat(np.arange(grid_size), grid_size)\n    pts = ax.scatter(grid_x, grid_y)\n\n    selector = SelectFromCollection(ax, pts)\n\n    print(\"Select points in the figure by enclosing them within a polygon.\")\n    print(\"Press the 'esc' key to start a new polygon.\")\n    print(\"Try holding the 'shift' key to move all of the vertices.\")\n    print(\"Try holding the 'ctrl' key to move a single vertex.\")\n\n    plt.show()\n\n    selector.disconnect()\n\n    # After figure is closed print the coordinates of the selected points\n    print('\\nSelected points:')\n    print(selector.xys[selector.ind])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        ".. admonition:: References\n\n   The use of the following functions, methods, classes and modules is shown\n   in this example:\n\n   - `matplotlib.widgets.PolygonSelector`\n   - `matplotlib.path.Path`\n\n"
      ]
    }
  ],
  "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.7"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}