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

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

https://dev59.com/64bhs4cB2Jgan1znbhB2 - tacaswell
https://dev59.com/02ox5IYBdhLWcg3wzXel#8956211 - tacaswell
https://dev59.com/2Gct5IYBdhLWcg3wuPq6#15724978 - tacaswell
还要查看animation模块,它将自动化计时器并为您处理blitting。 - tacaswell
2个回答

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()
如果你想要非常快速地进行操作,那么你应该考虑使用 blitting。

我也在寻找一种显示流图的方法。我尝试了这段代码,但是出现了“AttributeError: 'module' object has no attribute 'figure'” 的错误。然后我尝试使用“import matplotlib.pylab as plt”代替pylab,但是出现了“RuntimeError: xdata and ydata must be the same length”的错误。我的环境有问题吗?我正在使用Python 2.7。 - Gregory Danenberg
谢谢。这个更好...只需在 ln.set_xdata(range(len(data)) 后面加上 ")" 即可。 - Gregory Danenberg
@GregDan 谢谢,已添加缺失的 )。 - tacaswell
1
打开交互模式会导致当我从命令行运行脚本时图形不显示。这个使用 matplotlib.animation 的答案对我有用:https://dev59.com/w2855IYBdhLWcg3w5Icb - Jamie
2
这段代码在我的笔记本电脑上只显示一个空白图。Anaconda 3是全新安装的。 - João Abrantes

-1

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接