Boris L. Boris L. - 25 days ago 8
Python Question

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.

Answer

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)