11

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 :(
4

2 Answers 2

12
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.

Sign up to request clarification or add additional context in comments.

4 Comments

I'm also looking for a way to display streaming graph. I tried this piece of code and got "AttributeError: 'module' object has no attribute 'figure'". Then I tried to "import matplotlib.pylab as plt" instead of pylab and got "RuntimeError: xdata and ydata must be the same length". Something wrong with my environment? I'm using Python 2.7
Thanks. This one is better...just add ")" at ln.set_xdata(range(len(data))
Turning on interactive mode would cause the figure not to show when I run the script from the command line. This answer using matplotlib.animation worked for me: stackoverflow.com/questions/4098131/…
This code just shows a blank plot on my laptop. Brand new installation of Anaconda 3
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.