Using matplotlib's mpl_connect
functionality, one can bind events to function calls. However, the left and right arrow key are by default bound to go "back" and "forward" in the figure's history. I would like to disable this default binding.
For example:
import matplotlib.pyplot as plt
def on_key_press(event):
if event.key == "left":
print("Left!")
elif event.key == "right":
print("Right!")
plt.plot([0, 1, 2, 3, 4], [5, 2, 1, 2, 5])
plt.gcf().canvas.mpl_connect("key_press_event", on_key_press)
Pressing the left key will now print Left!
to the console. However, when we zoom into the figure, then the left key will also go "back", and zoom back out. (The right key will go "forward" and zoom back in.) I would like this to not happen - how do I do that? Making on_key_press
return False
doesn't do the trick.
(Background info: I have bindings set up so that, when the user clicks on the figure, a cursor will appear, centered on the plotted point (as given by [0,1,2,3,4] and [5,2,1,2,5]) that is closest to where the user clicked. I can make the left and right keys move this cursor to the previous/next data point, but if the user happens to be zoomed in, or has done any other manipulation to the graph, things go bad.)