2017-06-20 72 views
0

我希望圖形在參數值更改或定期更新時更新。我有以下代碼:根據參數更改自動更新圖形

a=0` 
b=50 
c=100 

def sine(x,y,l): 
    A=numpy.zeros(l) 
    for i in range(l): 
     A[i]=numpy.sin(2*math.pi*(i+x)/y) 
    return A 


def plot(l): 
    matplotlib.pyplot.clf() 
    matplotlib.pyplot.plot(l) 

plot(sine(a,b,c))` 

`

我如何重新運行繪圖功能,每次A/B/C被更新或定期?

回答

2

這裏那麼幾件事情,你應該瞭解正確的使用它,而無需遍歷他們ndarrays操作numpy的ufuncs的:

https://docs.scipy.org/doc/numpy-1.12.0/reference/ufuncs.html

其次,你必須有一個地方,一個更新事件被觸發,例如:

http://openbookproject.net/thinkcs/python/english3e/events.html

由於在這段代碼中沒有這樣的例子,我只是假設你知道那裏會發生什麼。無論發生哪種情況,您都需要處理該行以更新數據。

https://matplotlib.org/api/lines_api.html#matplotlib.lines.Line2D.set_xdata https://matplotlib.org/api/lines_api.html#matplotlib.lines.Line2D.set_ydata

下面是一些例子代碼高亮我相信你正在嘗試做的:

import numpy as np 
import matplotlib.pyplot as plt 

l = 100 
x = np.linspace(0, 2 * np.pi, l) 
y = np.sin(x) 

fig, ax = plt.subplots(1, 1) # generate figure and axes objects so that we have handles for them 
curve = ax.plot(x, y)[0] # capture the handle for the lines object so we can update its data later 

# now some kind of event happens where the data is changed, and we update the plot 
y = np.cos(x) # the data is changed! 
curve.set_ydata(y) 

# necessary if you are just executing this as a script 
# this example is a little more clear if executed stepwise in ipython 
plt.show(block=True) 
+0

是ufuncs比循環更有效? – Dole

+0

是的。除了代碼更清潔和更簡潔,計算上它可能快一個數量級,因爲整個計算是在一個c函數調用中處理的。事實上,循環一個numpy數組可能比循環一個python列表要慢,這是由於許多函數調用會在循環中產生的開銷 –