2017-03-02 20 views
0

我正嘗試在Python中創建一個繪圖的數據,其中正在繪製的數據在我的模擬進行時得到更新。在MATLAB中,我可以用下面的代碼做到這一點:python中的動態圖

t = linspace(0, 1, 100); 
figure 
for i = 1:100 
x = cos(2*pi*i*t); 
plot(x) 
drawnow 
end 

我試圖用matplotlibFuncAnimation功能animation模塊在做這個類中。它調用一個函數plot_voltage,它在我的模擬中重新計算每個時間步之後的電壓。我有它設置如下:

import matplotlib.pyplot as plt 
import matplotlib.animation as animation 

def __init__(self): 
    ani = animation.FuncAnimation(plt.figure(2), self.plot_voltage) 
    plt.draw() 

def plot_voltage(self, *args): 
    voltages = np.zeros(100) 
    voltages[:] = np.nan 

    # some code to calculate voltage 

    ax1 = plt.figure(2).gca() 
    ax1.clear() 
    ax1.plot(np.arange(0, len(voltages), 1), voltages, 'ko-')` 

當我的模擬運行,數字顯示了,但只是凍結。但是,代碼無誤地運行。有人能讓我知道我錯過了什麼嗎?

+0

我會適應的第三個版本爲[這個答案](http://stackoverflow.com/questions/28074461/animating-growing -line積合蟒-matplotlib?RQ = 1)。 – cphlewis

+0

謝謝@cphlewis。這個解決方案的問題是,如果我有另一個函數,比如'count()',它只是計算正整數,我在'plt.show()'後面運行這個函數,'count()'不會運行直到我關閉了情節。用'plt.draw()'代替'plt.show()'會導致圖不顯示,但是'count()'運行。如何在程序繼續並且count()運行時更新圖表?我的後端是Qt5Agg上的交互模式。 –

+0

在第三種解決方案中,update()會調用你的count(),所以繪圖繼續。 – cphlewis

回答

1

下面是使用FuncAnimation的MATLAB代碼爲matplotlib的翻譯:

import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.animation as animation 

t = np.linspace(0, 1, 100) 
fig = plt.figure() 
line, = plt.plot([],[]) 

def update(i): 
    x = np.cos(2*np.pi*i*t) 
    line.set_data(t,x) 

ani = animation.FuncAnimation(fig, update, 
       frames=np.linspace(1,100,100), interval=100) 
plt.xlim(0,1) 
plt.ylim(-1,1) 
plt.show() 
+0

謝謝,但您上面的評論是正確的 - 我應該更清楚。我有一個對象的參數正在更新的模擬。每次執行更新時,我都想繪製它們的值。 [這裏](https://gist.github.com/anonymous/e5a073a08286397368804526dcafe95e)是一個簡單的例子。我不一定需要使用'animation'軟件包。這只是我正在嘗試的東西。當我運行這個例子時,數字不渲染,窗口不響應。當我按CTRL + C終端時,數字繪圖,但程序停止。任何關於最佳方式的想法? –

+0

我在下面評論[GiHubGist的代碼](https://gist.github.com/anonymous/e5a073a08286397368804526dcafe95e?signup=true)。 – ImportanceOfBeingErnest