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

Posted

技术标签:

【中文标题】你可以在 matplotlib 中绘制实时数据吗?【英文标题】:Can you plot live data in 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 :(

【问题讨论】:

***.com/questions/14665636/… ***.com/questions/8955869/… ***.com/questions/11874767/… 还可以查看animation 模块,该模块将自动执行计时器并为您处理 blitting。 【参考方案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 的这个答案对我有用:***.com/questions/4098131/… 这段代码只是在我的笔记本电脑上显示了一个空白图。全新安装 Anaconda 3

以上是关于你可以在 matplotlib 中绘制实时数据吗?的主要内容,如果未能解决你的问题,请参考以下文章

在 tkinter 画布中嵌入来自 Arduino 的 Matplotlib 实时绘图数据

使用 Matplotlib 在 Python 中绘制时间

Python/MatPlotLib:无法在 y 轴上打印正确的数据

Pyqt+matplotlib 实现实时画图案例

Pyqt+matplotlib 实现实时画图案例

Pyqt+matplotlib 实现实时画图案例