import matplotlib.pyplot as plt
from matplotlib.widgets import PolygonSelector

# To create the polygon programmatically
fig, ax = plt.subplots()

selector = PolygonSelector(ax, lambda *args: None)

# Add three vertices
selector.verts = [(0.1, 0.4), (0.5, 0.9), (0.3, 0.2)]

# To create the polygon interactively

fig2, ax2 = plt.subplots()

selector2 = PolygonSelector(ax2, lambda *args: None)

print("Click on the figure to create a polygon.")
print("Press the 'esc' key to start a new polygon.")
print("Try holding the 'shift' key to move all of the vertices.")
print("Try holding the 'ctrl' key to move a single vertex.")


Shows how one can select indices of a polygon interactively.

import numpy as np

from matplotlib.widgets import PolygonSelector
from matplotlib.path import Path

class SelectFromCollection:
    Select indices from a matplotlib collection using `PolygonSelector`.
    Selected indices are saved in the `ind` attribute. This tool fades out the
    points that are not part of the selection (i.e., reduces their alpha
    values). If your collection has alpha < 1, this tool will permanently
    alter the alpha values.
    Note that this tool selects collection objects based on their *origins*
    (i.e., `offsets`).
    ax : `~matplotlib.axes.Axes`
        Axes to interact with.
    collection : `matplotlib.collections.Collection` subclass
        Collection you want to select from.
    alpha_other : 0 <= float <= 1
        To highlight a selection, this tool sets all selected points to an
        alpha value of 1 and non-selected points to *alpha_other*.

    def __init__(self, ax, collection, alpha_other=0.3):
        self.canvas = ax.figure.canvas
        self.collection = collection
        self.alpha_other = alpha_other

        self.xys = collection.get_offsets()
        self.Npts = len(self.xys)

        # Ensure that we have separate colors for each object
        self.fc = collection.get_facecolors()
        if len(self.fc) == 0:
            raise ValueError('Collection must have a facecolor')
        elif len(self.fc) == 1:
            self.fc = np.tile(self.fc, (self.Npts, 1))

        self.poly = PolygonSelector(ax, self.onselect, draw_bounding_box=True)
        self.ind = []

    def onselect(self, verts):
        path = Path(verts)
        self.ind = np.nonzero(path.contains_points(self.xys))[0]
        self.fc[:, -1] = self.alpha_other
        self.fc[self.ind, -1] = 1

    def disconnect(self):
        self.fc[:, -1] = 1

if __name__ == '__main__':
    import matplotlib.pyplot as plt

    fig, ax = plt.subplots()
    grid_size = 5
    grid_x = np.tile(np.arange(grid_size), grid_size)
    grid_y = np.repeat(np.arange(grid_size), grid_size)
    pts = ax.scatter(grid_x, grid_y)

    selector = SelectFromCollection(ax, pts)

    print("Select points in the figure by enclosing them within a polygon.")
    print("Press the 'esc' key to start a new polygon.")
    print("Try holding the 'shift' key to move all of the vertices.")
    print("Try holding the 'ctrl' key to move a single vertex.")


    # After figure is closed print the coordinates of the selected points
    print('\nSelected points:')

Related articles

matplotlib radio buttons

Using radio buttons to choose properties of your plot. Radio buttons let you choose between multiple options in a visualization. In this case, the buttons let the user choose one of the three different sine waves to be shown in the plot.

sanic delayed response

from asyncio import sleep from sanic import Sanic, response app = Sanic("DelayedResponseApp", strict_slashes=True) app.config.AUTO_EXTEND = False

sanic exception monitoring

from sanic.exceptions import SanicException from sanic.handlers import ErrorHandler class CustomHandler(ErrorHandler): def default(self, request, exception): # Here, we have access to the exception object

sanic logging

import logging from sanic import Sanic, text logging_format = "[%(asctime)s] %(process)d-%(levelname)s " logging_format += "%(module)s::%(funcName)s():l%(lineno)d: " logging_format += "%(message)s"

pytest-xdist example for sanic server

Install testing tools: $ pip install pytest pytest-xdist Run with xdist params: $ pytest examples/ -n 8 # 8 workers example import re import pytest

sanic raygun

from os import getenv from raygun4py.raygunprovider import RaygunSender from sanic import Sanic from sanic.exceptions import SanicException from sanic.handlers import ErrorHandler

sanic redirect

from sanic import Sanic, response app = Sanic("Example") @app.route("/") def handle_request(request):     return response.redirect("/redirect")

matplotlib Rectangle and ellipse selectors

Click somewhere, move the mouse, and release the mouse button. `.RectangleSelector` and `.EllipseSelector` draw a rectangle or an ellipse from the initial click position to the current mouse position (within the same axes) until the button is released

matplotlib slider

In this example, sliders are used to control the frequency and amplitude of a sine wave. See :doc:`/gallery/widgets/slider_snap_demo` for an example of having

matplotlib slider snap

Snapping Sliders to Discrete Values You can snap slider values to discrete values using the ``valstep`` argument. In this example the Freq slider is constrained to be multiples of pi, and the Amp slider uses an array as the ``valstep``