11

我正在一个线程中从套接字读取数据,并希望在新数据到达时绘制和更新绘图。我编写了一个小原型来模拟事物,但它不起作用:

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

如果你想走得很快,你应该研究一下blitting。

于 2013-09-13T19:02:26.043 回答
-1

f.show()不会阻塞,可以draw用来更新图。

f = pylab.figure()
f.show()
while True:
    time.sleep(1)
    pylab.plot(data)
    pylab.draw()
于 2013-09-13T17:31:42.223 回答