You are reading an old version of the documentation (v1.5.0). For the latest version see

We're updating the default styles for Matplotlib 2.0

Learn what to expect in the new updates


Previous topic

event_handling example code:

Next topic

event_handling example code:

This Page

event_handling example code: looking_glass.pyΒΆ

[source code]

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
x, y = np.random.rand(2, 200)

fig, ax = plt.subplots()
circ = patches.Circle((0.5, 0.5), 0.25, alpha=0.8, fc='yellow')

ax.plot(x, y, alpha=0.2)
line, = ax.plot(x, y, alpha=1.0, clip_path=circ)

class EventHandler(object):
    def __init__(self):
        fig.canvas.mpl_connect('button_press_event', self.onpress)
        fig.canvas.mpl_connect('button_release_event', self.onrelease)
        fig.canvas.mpl_connect('motion_notify_event', self.onmove)
        self.x0, self.y0 =
        self.pressevent = None

    def onpress(self, event):
        if event.inaxes != ax:

        if not circ.contains(event)[0]:

        self.pressevent = event

    def onrelease(self, event):
        self.pressevent = None
        self.x0, self.y0 =

    def onmove(self, event):
        if self.pressevent is None or event.inaxes != self.pressevent.inaxes:

        dx = event.xdata - self.pressevent.xdata
        dy = event.ydata - self.pressevent.ydata = self.x0 + dx, self.y0 + dy

handler = EventHandler()

Keywords: python, matplotlib, pylab, example, codex (see Search examples)