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.
The best use of Matplotlib differs depending on how you are using it; roughly, the three applicable contexts are using Matplotlib in a script, in an IPython terminal, or in an IPython notebook.
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With