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

nic*_*ine 10 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 :(
Run Code Online (Sandbox Code Playgroud)

tac*_*ell 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()
Run Code Online (Sandbox Code Playgroud)

如果你想要快速前进,你应该考虑一下blitting.

  • 这段代码仅在我的笔记本电脑上显示了一个空白图。全新安装 Anaconda 3 (2认同)