Join the Stack Overflow Community
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I have a Python program (main.py) that has a constant stream of data that is handled by a class RTStreamer which basically gets the data -- via a live stream -- and appends it to a numpy array. However I would like to actually visualize the data as it is coming in which is where tkinter and matplotlib come in. In another python file (gui.py) I have a live plot using matplotlib animations and a button to trigger my first file (main.py) to start streaming the data. However when I click the button to start streaming the data I can see on my console that it is getting the data and appending it to the array (because I am printing the array), however the chart does not update at all.

Here is a simplified version of what my main.py looks like:

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()

An here is what my gui.py looks like:

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()  

I've noticed if I hit CTRL+C to break the program, it strops streaming data and plots the array, and if I hit CTRL+C again it closes the matplotlib window altogether. However I would like to stream and append to the array while also plotting it, any ideas on how I can accomplish this? Thanks.

share|improve this question

To make your code work, you need to draw the artist on each frame, not just show the canvas. However, that will be effing slow. What you really want to do, is to only update the data, and keep as much of the canvas constant. For that you use blit. Minimum working example below.

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
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.