11

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.)

2 Answers 2

13

To remove all of the default key bindings

fig = plt.gcf()
fig.canvas.mpl_disconnect(fig.canvas.manager.key_press_handler_id)

however this is using a sledge hammer when you need a scalpel. Looking at the handler function the default key bindings are pulled from the rcparams so

import matplotlib as mpl
mpl.rcParams['keymap.back'].remove('left')
mpl.rcParams['keymap.forward'].remove('right')

will disable just the 'left' and 'right' keys.

Those remove calls should probably be wrapped in try...except as they will raise if the value is not in the list (ex, your users already re-mapped them). It might be worth looping over all of the rcparams used by the handler to make sure none of them conflict.

2
  • Still somewhat of a sledgehammer, as this disables it for every axes in figure, but it's good enough for me. Thanks!
    – acdr
    Feb 26, 2016 at 9:40
  • The other option is to remove the callback on a per axes basis and replace it will a vendored modified version of the default key handler.
    – tacaswell
    Feb 26, 2016 at 11:24
2

In order to find the other Key maps......

  import matplotlib as mpl 
    for k,v in mpl.rcParams.items():
      if -1 != k.find("keymap"):
        print "rcParams[%s]=%s"%(k,v)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.