{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Keypress event\n\nShow how to connect to keypress events.\n\n

Note

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.

\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import sys\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef on_press(event):\n print('press', event.key)\n sys.stdout.flush()\n if event.key == 'x':\n visible = xl.get_visible()\n xl.set_visible(not visible)\n fig.canvas.draw()\n\n\n# Fixing random state for reproducibility\nnp.random.seed(19680801)\n\nfig, ax = plt.subplots()\n\nfig.canvas.mpl_connect('key_press_event', on_press)\n\nax.plot(np.random.rand(12), np.random.rand(12), 'go')\nxl = ax.set_xlabel('easy come, easy go')\nax.set_title('Press a key')\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.13.2" } }, "nbformat": 4, "nbformat_minor": 0 }