Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you plot live data in matplotlib?

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 work:

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

    pylab.figure()

    while True:
        time.sleep(1)
        pylab.plot(data)
        pylab.show() # This blocks :(
like image 434
nickponline Avatar asked Sep 13 '13 17:09

nickponline


People also ask

Does matplotlib work in idle?

Download the “Install Matplotlib (for PC). bat” file from my web site, and double-click it to run it. Test your installation. Start IDLE (Python 3.4 GUI – 32 bit), type “import matplotlib”, and confirm that this command completes without an error.

Is there anything better than matplotlib?

Plotly has several advantages over matplotlib. One of the main advantages is that only a few lines of codes are necessary to create aesthetically pleasing, interactive plots. The interactivity also offers a number of advantages over static matplotlib plots: Saves time when initially exploring your dataset.


1 Answers

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.

like image 166
tacaswell Avatar answered Oct 12 '22 14:10

tacaswell