2016-10-04 59 views
0

我有一個Python程序(main.py)有一個恆定的數據流,由一個RTStreamer類基本上獲取數據 - 通過一個實時流 - 並將其附加到一個numpy數組。然而,我想實際上可視化的數據,因爲它是在哪裏tkinter和matplotlib進來。在另一個python文件(gui.py)我有一個使用matplotlib動畫和一個按鈕來觸發我的第一個文件(main.py)開始流式傳輸數據。然而,當我點擊按鈕開始流式傳輸數據時,我可以在控制檯上看到它正在獲取數據並將其附加到數組(因爲我在打印數組),但是圖表根本不會更新。運行一個函數,更新數組雖然Matplotlib繪製它

這裏是什麼我main.py看起來像一個簡化版本:

closeBidArray = np.array([]) 

class RTStreamer(stream.Streamer): 
    def __init__(self, *args, **kwargs): 
     super(RTStreamer, self).__init__(*args, **kwargs) 
     print(datetime.now(), "initialized") 

    def on_success(self, data): 
     # get data and append it to closeBidArray 

    def on_error(self, data): 
     # disconnect 

def run(): 
    stream = RTStreamer() 
    stream.rates() 

的這裏是我的gui.py樣子:

import main # in order to get closeBidArray 

figure = Figure(figsize=(5,5), dpi=100) 
subplot1 = figure.add_subplot(111) 


class App(tk.Tk): 
    # Mostly to do with formatting the window and frames in it 

def animate(): 
    subplot1.clear 
    subplot1.plot(main.closeBidArray) 

class MainPage(tk.Frame): 
    def __init__(self, parent, controller): 
     tk.Frame.__init__(self, parent) 

     # THIS IS THE BUTTON THAT TRIGGERS TO FUNCTION THAT STREAMS THE DATA: 
     button1 = tk.Button(text="Hi", command=main.run) 
     button1.pack() 

     canvas = FigureCanvasTkAgg(figure, self) 
     canvas.show() 
     canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True) 

app = App() 
ani = animation.FuncAnimation(figure, animate, interval=1000) 
app.mainloop() 

我已經注意如果我擊中了CTRL + C打破該程序,它會延長流數據並繪製陣列,並且如果我點擊了CTRL + C它再次關閉matplotlib窗口。然而,我想流並追加到陣列,同時也繪製它,任何想法,我怎麼能做到這一點?謝謝。

回答

0

爲了使您的代碼正常工作,您需要在每個框架上繪製藝術家,而不僅僅是顯示畫布。然而,這將是緩慢的。你真正想要做的只是更新數據,並保持畫布不變。爲此你使用blit。下面的最小工作示例。

import numpy as np 
import matplotlib.pyplot as plt 

def animate(movie): 
    """ 
    Animate frames in array using blit. 

    Arguments: 
    ---------- 
     movie: (time, height, width) ndarray 

    """ 

    plt.ion() 
    fig, ax = plt.subplots(1,1) 

    # initialize blit for movie axis 
    img = ax.imshow(np.zeros((movie.shape[1],movie.shape[2])), 
        interpolation = 'nearest', origin = 'lower', vmin = 0, vmax = 1, cmap = 'gray') 

    # cache the background 
    bkg = fig.canvas.copy_from_bbox(ax.bbox) 

    # loop over frames 
    raw_input('Press any key to start the animation...') 
    for t in range(movie.shape[0]): 
     # draw movie 
     img.set_data(movie[t]) 
     fig.canvas.restore_region(bkg) 
     ax.draw_artist(img) 
     fig.canvas.blit(ax.bbox) 

    return 

if __name__ == "__main__": 
    movie = np.random.rand(1000, 10, 10) 
    animate(movie) 
    pass 
相關問題