Boris L.
Boris L.

Reputation: 998

How to close a python figure by keyboard input?

I'm trying to write a python program that displays a figure for indefinite time and closes it after any keyboard key is pressed.

In fact, the python program should do the same as this Matlab code:

t = 0:0.01:2;
s = sin(2 * pi * t);

plot(t,s)

pause
close

In python I'm able to plot the figure but nothing happens after the keyboard input.

import numpy as np
import matplotlib.pyplot as plt

t = np.arange(0.0, 2.0, 0.01)
s = np.sin(2*np.pi*t)

#plt.ion()
fig = plt.figure()
plt.plot(t,s)
#plt.show()
plt.draw()

raw_input("PRESS ANY KEY TO CONTINUE.")
plt.close(fig)

So far I observed that plt.close(fig) does not do anything in conjunction with plt.show(). However, when I use plt.draw() instead, plt.close(fig) is closing the figure. Yet, when I add raw_input("PRESS ANY KEY TO CONTINUE.") into my program, the figure does not appear at all.

What am I doing wrong?

I also tried experimenting with plt.ion(), but without success.

Upvotes: 20

Views: 25647

Answers (3)

simon
simon

Reputation: 5133

As of writing (December 2021, using Matplotlib 3.5 on Windows), pressing the q key now seems to close a figure by default – at least with the Tk and Qt GUI backends that I tried. If another specific key is desired instead, e.g. the escape key, one might want to follow the solution provided in this discussion, which uses event handling:

import matplotlib.pyplot as plt
import numpy as np

def close_figure(event):
    if event.key == 'escape':
        plt.close(event.canvas.figure)

t = np.arange(0.0, 2.0, 0.01)
s = np.sin(2 * np.pi * t)

plt.plot(t, s)
plt.gcf().canvas.mpl_connect('key_press_event', close_figure)
plt.show()

Upvotes: 3

Guillem Cucurull
Guillem Cucurull

Reputation: 1691

I think that using plt.waitforbuttonpress(0) could solve the trick of using raw_input():

import numpy as np
import matplotlib.pyplot as plt

t = np.arange(0.0, 2.0, 0.01)
s = np.sin(2*np.pi*t)

fig = plt.figure()
plt.plot(t,s)
plt.draw()
plt.waitforbuttonpress(0) # this will wait for indefinite time
plt.close(fig)

Upvotes: 22

Joran Beasley
Joran Beasley

Reputation: 113988

something like this maybe ?

import numpy as np
import matplotlib.pyplot as plt

t = np.arange(0.0, 2.0, 0.01)
s = np.sin(2*np.pi*t)


fig = plt.figure()
plt.plot(t,s)
#plt.show()
plt.draw()
plt.pause(1) # <-------
raw_input("<Hit Enter To Close>")
plt.close(fig)

Upvotes: 11

Related Questions