2016-10-04 58 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 
相关问题