Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

python - view and then close the figure automatically in matplotlib?

I have to check whether my parameters setting is right, so I need to draw many plots, and for drawing these plots, I choose to use matplotlib. After each checking, I need to click the close button on the top left conner. It's trivial. So is there any method that can make the plot show in about 3 or 5 seconds and automatically close without clicking? I know about the plt.close(), but it doesn't work. Here is my code.

from math import *
import sys
import numpy as np
from scipy import special 
import matplotlib.pyplot as plt

x1=[]
y1=[]
x2=[]
y2=[]
x3=[]
y3=[]
with open('fort.222','r') as f:
    for line in f:
        a,b=line.split()
        x1.append(float(a))
        y1.append(float(b))

n=int(sys.argv[1])
i=0
with open('fort.777','r') as f:
    for line in f:
        if i==0:
            k1=float(line)
        i=i+1

x1,y1=np.array(x1),np.array(y1)

z1=special.eval_hermite(n,x1*k1)*sqrt(1/(sqrt(pi)*pow(2,n)*factorial(n)))*sqrt(k1)*np.exp(-np.power(k1*x1,2)/2.)                                                                                                  
plt.figure()
plt.plot(x1,z1)
plt.plot(x1,y1)
plt.plot(x1,np.zeros(len(x1)))
plt.title('single center & double center')
plt.xlim(x1.min(),x1.max())
plt.ylim(-max(abs(y1.min()-0.1),y1.max()+0.1),max(abs(y1.min()-0.2),y1.max()+0.2))
plt.xlabel('$zeta$'+'/fm')
plt.legend(('single, n='+sys.argv[1],'double, n='+sys.argv[1]),loc=2,frameon=True)

plt.show()
plt.close()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Documentation on pyplot.show() reads:

matplotlib.pyplot.show(*args, **kw)

Display a figure. When running in ipython with its pylab mode, display all figures and return to the ipython prompt.

In non-interactive mode, display all figures and block until the figures have been closed; in interactive mode it has no effect unless figures were created prior to a change from non-interactive to interactive mode (not recommended). In that case it displays the figures but does not block.

A single experimental keyword argument, block, may be set to True or False to override the blocking behavior described above.

So the solution is this:

plt.show(block=False)
plt.pause(3)
plt.close()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...