你能在matplotlib中绘制实时数据吗?

时间:2013-09-13 17:10:58

标签: python matplotlib

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

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

2 个答案:

答案 0 :(得分:10)

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。

答案 1 :(得分:-1)

f.show()没有阻止,您可以使用draw来更新数字。

f = pylab.figure()
f.show()
while True:
    time.sleep(1)
    pylab.plot(data)
    pylab.draw()