2013-07-03 430 views
1

我正在繪製使用matplotlib的線,並希望在生成新值後立即更新線數據。但是,一旦進入循環,就不會出現窗口。即使打印的行表示循環正在運行。動態更新python中的圖形線

這裏是我的代碼:

def inteprolate(u,X): 
    ... 
    return XX 

# generate initial data 
XX = inteprolate(u,X) 

#initial plot 
xdata = XX[:,0] 
ydata = XX[:,1] 
ax=plt.axes() 
line, = plt.plot(xdata,ydata) 

# If this is in, The plot works the first time, and then pauses 
# until the window is closed. 
# plt.show() 

# get new values and re-plot 
while True: 
    print "!" 
    XX = inteprolate(u,XX) 
    line.set_xdata(XX[:,0]) 
    line.set_ydata(XX[:,1]) 
    plt.draw() # no window 

如何更新我的陰謀實時當plt.show()阻塞和plt.draw不更新/顯示窗口?

+0

also http://stackoverflow.com/questions/16447812/make-matplotlib-draw-only-show-new-point/16448826#16448826 – tacaswell

回答

1

你需要調用plt.pause在循環給予GUI有機會處理所有你給它來處理事件。如果你不這樣做,它可以得到備份,永遠不會顯示你的圖表。

# get new values and re-plot 
plt.ion() # make show non-blocking 
plt.show() # show the figure 
while True: 
    print "!" 
    XX = inteprolate(u,XX) 
    line.set_xdata(XX[:,0]) 
    line.set_ydata(XX[:,1]) 
    plt.draw() # re-draw the figure 
    plt.pause(.1) # give the gui time to process the draw events 

如果你想做動畫,你應該學會如何使用animation模塊。請參閱awesome tutorial開始。

0

我覺得這個玩具代碼澄清@ardoi的答案:

import matplotlib.pyplot as plt 
import numpy as np 

x = np.linspace(0,2*np.pi,num=100) 
plt.ion() 
for i in xrange(x.size): 
    plt.plot(x[:i], np.sin(x[:i])) 
    plt.xlim(0,2*np.pi) 
    plt.ylim(-1,1) 
    plt.draw() 
    plt.clf() 

編輯: 上面的代碼顯示在屏幕上製作動畫的正弦函數。

+0

你能解釋一下代碼的作用嗎?謝謝。 – stanri

0

一種有效的方式做同樣的@Alejandro是:

import matplotlib.pyplot as plt 
import numpy as np 

plt.ion() 
x = np.linspace(0,2*np.pi,num=100) 
y = np.sin(x) 

plt.xlim(0,2*np.pi) 
plt.ylim(-1,1) 
plot = plt.plot(x[0], y[0])[0] 
for i in xrange(x.size): 
    plot.set_data(x[0:i],y[0:i]) 
    plt.draw() 
+0

你能解釋一下代碼的作用嗎?謝謝。 – stanri

+0

這與OP中的代碼有何不同?你只是以不同的方式使用'set_data'。另外,使用'plot'作爲變量名是非常糟糕的風格。 – tacaswell