{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Looking glass\n\nExample using mouse events to simulate a looking glass for inspecting data.\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\nimport matplotlib.patches as patches\n\n# Fixing random state for reproducibility\nnp.random.seed(19680801)\n\nx, y = np.random.rand(2, 200)\n\nfig, ax = plt.subplots()\ncirc = patches.Circle((0.5, 0.5), 0.25, alpha=0.8, fc='yellow')\nax.add_patch(circ)\n\n\nax.plot(x, y, alpha=0.2)\nline, = ax.plot(x, y, alpha=1.0, clip_path=circ)\nax.set_title(\"Left click and drag to move looking glass\")\n\n\nclass EventHandler:\n def __init__(self):\n fig.canvas.mpl_connect('button_press_event', self.on_press)\n fig.canvas.mpl_connect('button_release_event', self.on_release)\n fig.canvas.mpl_connect('motion_notify_event', self.on_move)\n self.x0, self.y0 = circ.center\n self.pressevent = None\n\n def on_press(self, event):\n if event.inaxes != ax:\n return\n\n if not circ.contains(event)[0]:\n return\n\n self.pressevent = event\n\n def on_release(self, event):\n self.pressevent = None\n self.x0, self.y0 = circ.center\n\n def on_move(self, event):\n if self.pressevent is None or event.inaxes != self.pressevent.inaxes:\n return\n\n dx = event.xdata - self.pressevent.xdata\n dy = event.ydata - self.pressevent.ydata\n circ.center = self.x0 + dx, self.y0 + dy\n line.set_clip_path(circ)\n fig.canvas.draw()\n\nhandler = EventHandler()\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 }