Search code examples
pythonmatplotlibosx-mavericks

Close pyplot figure using the keyboard on Mac OS X


Is there a way to close a pyplot figure in OS X using the keyboard (as far as I can see you can only close it by clicking the window close button)?

I tried many key combinations like command-Q, command-W, and similar, but none of them appear to work on my system.

I also tried this code posted here:

#!/usr/bin/env python

import matplotlib.pyplot as plt

plt.plot(range(10))

def quit_figure(event):
    if event.key == 'q':
        plt.close(event.canvas.figure)

cid = plt.gcf().canvas.mpl_connect('key_press_event', quit_figure)

plt.show()

However, the above doesn't work on OS X either. I tried adding print statements to quit_figure, but it seems like it's never called.

I'm trying this on the latest public OS X, matplotlib version 1.1.1, and the standard Python that comes with OS X (2.7.3). Any ideas on how to fix this? It's very annoying to have to reach for the mouse every time.


Solution

  • This is definitely a bug in the default OS X backend used by pyplot. Adding the following two lines at the top of the file switches to a different backend that works for me, if this helps anyone else.

    import matplotlib
    matplotlib.use('TKAgg')