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 :(
nickponline
  • 25,354
  • 32
  • 99
  • 167

2 Answers2

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

tacaswell
  • 84,579
  • 22
  • 210
  • 199
  • 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 – Gregory Danenberg May 25 '15 at 06:27
  • Thanks. This one is better...just add ")" at ln.set_xdata(range(len(data)) – Gregory Danenberg May 26 '15 at 11:51
  • 1
    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: http://stackoverflow.com/questions/4098131/how-to-update-a-plot-in-matplotlib – Jamie Sep 17 '16 at 19:16
  • 2
    This code just shows a blank plot on my laptop. Brand new installation of Anaconda 3 – João Abrantes Mar 08 '18 at 07:52
-1

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()
mattexx
  • 6,456
  • 3
  • 36
  • 47