Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 782
Boris L. Avatar asked Apr 06 '14 20:04

Boris L.


People also ask

Can you use Matplotlib in terminal?

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.


2 Answers

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)
like image 91
Guillem Cucurull Avatar answered Sep 18 '22 15:09

Guillem Cucurull


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)
like image 44
Joran Beasley Avatar answered Sep 18 '22 15:09

Joran Beasley