Can you plot live data in matplotlib?

后端 未结 2 1609
心在旅途
心在旅途 2020-12-01 10:12

I\'m reading data from a socket in one thread and would like to plot and update the plot as new data arrives. I coded up a small prototype to simulate things but it doesn\'t

相关标签:
2条回答
  • 2020-12-01 10:31
    import matplotlib.pyplot as plt
    import time
    import threading
    import random
    
    data = []
    
    # This just simulates reading from a socket.
    def data_listener():
        while True:
            time.sleep(1)
            data.append(random.random())
    
    if __name__ == '__main__':
        thread = threading.Thread(target=data_listener)
        thread.daemon = True
        thread.start()
        #
        # initialize figure
        plt.figure() 
        ln, = plt.plot([])
        plt.ion()
        plt.show()
        while True:
            plt.pause(1)
            ln.set_xdata(range(len(data)))
            ln.set_ydata(data)
            plt.draw()
    

    If you want to go really fast, you should look into blitting.

    0 讨论(0)
  • 2020-12-01 10:42

    f.show() does not block, and you can use draw to update the figure.

    f = pylab.figure()
    f.show()
    while True:
        time.sleep(1)
        pylab.plot(data)
        pylab.draw()
    
    0 讨论(0)
提交回复
热议问题