Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 593
houbysoft Avatar asked Jun 23 '14 18:06

houbysoft


People also ask

What does PLT close () do?

close() Function. The close() function in pyplot module of matplotlib library is used to close a figure window.


1 Answers

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')
like image 200
houbysoft Avatar answered Sep 20 '22 00:09

houbysoft