Here is the explanation of how it works:
- fig, ax = plt.subplots() defines and instantiates the figure and axis objects.
- ax.plot(x ,y, 'go-', label='sin') and ax.plot(x, y1, 'bd-', label='cos') plot the sine and cosine functions.
- lg = ax.legend(loc='upper center', fontsize=15) and ax.set_title('Press a key', size=25) set the legend and title for the plot. Here, we capture the legend in a variable, lg, which will be used in the callback function later.
- fig.canvas.mpl_connect() is the method that captures the events from the backend and connects them to the corresponding callback functions to respond to the events. This is equivalent to the handle_event() function we defined in the previous recipe.
- fig.canvas.mpl_connect('key_press_event', ...