【问题标题】:Can you plot live data in matplotlib?你可以在 matplotlib 中绘制实时数据吗?
【发布时间】:2013-09-18 11:03:10
【问题描述】:

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

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

【问题讨论】:

标签: python matplotlib


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:
    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'对象没有属性'figure'”。然后我尝试“将 matplotlib.pylab 作为 plt 导入”而不是 pylab 并得到“RuntimeError:xdata 和 ydata 必须是相同的长度”。我的环境有问题吗?我正在使用 Python 2.7
    • 谢谢。这个更好...只需在 ln.set_xdata(range(len(data)) 处添加“)”
    • @GregDan 谢谢,添加了缺失的)
    • 打开交互模式会导致当我从命令行运行脚本时图形不显示。使用matplotlib.animation 的这个答案对我有用:stackoverflow.com/questions/4098131/…
    • 这段代码只是在我的笔记本电脑上显示了一个空白图。全新安装 Anaconda 3
    猜你喜欢
    • 2020-09-24
    • 2019-08-21
    • 2012-10-22
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    • 2020-08-23
    • 2020-08-25
    • 2021-11-03
    相关资源
    最近更新 更多