使用python中的matplotlib 畫圖,show後關閉窗口,繼續運行命令

使用python中的matplotlib 畫圖,show後關閉窗口,繼續運行命令

 

在用python中的matplotlib 畫圖時,show()函數老是要放在最後,且它阻止命令繼續往下運行,直到1.0.1版本才支持多個show()的使用。
想在顯示圖像後繼續運行相關的處理命令,或者顯示一副圖像後關閉它,再顯示第二幅圖像。以下辦法:

首先搜索到:
plt.close() will close current instance.
plt.close(2) will close figure 2
plt.close(plot1) will close figure with instance plot1
plt.close('all') will close all fiures
Found here.
Remember that plt.show() is a blocking function, so in the example code you used above,plt.close() isn't being executed until the window is closed, which makes it redundant.
You can use plt.ion() at the beginning of your code to make it non-blocking, although this has other implications.

搜索到:http://matplotlib.org/faq/usage_faq.html#what-is-interactive-mode

總結以下例子:
import matplotlib.pyplot as plt
import time
plt.ion() #開啓interactive mode
x = np.linspace(0, 50, 1000)
plt.figure(1) # 建立圖表1
plt.plot(x, np.sin(x))
plt.draw()
time.sleep(5)
plt.close(1)
plt.figure(2) # 建立圖表2
plt.plot(x, np.cos(x))
plt.draw()
time.sleep(5)
print 'it is ok'

若是不須要關閉圖表1,去掉plt.close(1),若是不須要redraw the current figure,那也能夠去掉plt.draw()
html

相關文章
相關標籤/搜索