1""" 2============== 3Keypress event 4============== 5 6Show how to connect to keypress events. 7""" 8import sys 9import numpy as np 10import matplotlib.pyplot as plt 11 12 13def on_press(event): 14 print('press', event.key) 15 sys.stdout.flush() 16 if event.key == 'x': 17 visible = xl.get_visible() 18 xl.set_visible(not visible) 19 fig.canvas.draw() 20 21 22# Fixing random state for reproducibility 23np.random.seed(19680801) 24 25fig, ax = plt.subplots() 26 27fig.canvas.mpl_connect('key_press_event', on_press) 28 29ax.plot(np.random.rand(12), np.random.rand(12), 'go') 30xl = ax.set_xlabel('easy come, easy go') 31ax.set_title('Press a key') 32plt.show() 33