与实时 matplotlib 图交互 [英] Interacting with live matplotlib plot

查看:33
本文介绍了与实时 matplotlib 图交互的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个实时绘图,该绘图会随着更多数据可用而更新.

I'm trying to create a live plot which updates as more data is available.

import os,sys
import matplotlib.pyplot as plt

import time
import random

def live_plot():
    fig = plt.figure()
    ax = fig.add_subplot(111)

    ax.set_xlabel('Time (s)')
    ax.set_ylabel('Utilization (%)')
    ax.set_ylim([0, 100])
    ax.set_xlim(left=0.0)

    plt.ion()
    plt.show()

    start_time = time.time()
    traces = [0]
    timestamps = [0.0]
    # To infinity and beyond
    while True:
        # Because we want to draw a line, we need to give it at least two points
        # so, we pick the last point from the previous lists and append the
        # new point to it. This should allow us to create a continuous line.
        traces = [traces[-1]] + [random.randint(0, 100)]
        timestamps = [timestamps[-1]] + [time.time() - start_time]
        ax.set_xlim(right=timestamps[-1])
        ax.plot(timestamps, traces, 'b-')
        plt.draw()
        time.sleep(0.3)

def main(argv):
    live_plot()

if __name__ == '__main__':
    main(sys.argv)

上面的代码有效.但是,我无法与 plt.show()

The above code works. However, I'm unable to interact with the window generated by plt.show()

如何在能够与绘图窗口交互的同时绘制实时数据?

How can I plot live data while still being able to interact with the plot window?

推荐答案

使用 plt.pause()代替 time.sleep().

后者只是保持主线程的执行,GUI 事件循环不运行.相反, plt.pause 运行事件循环,并允许您与该图进行交互.

The latter simply holds execution of the main thread and the GUI event loop does not run. Instead, plt.pause runs the event loop and allows you to interact with the figure.

来自文档:

暂停间隔秒.

如果有活动图形,将对其进行更新和显示,并且GUI事件循环将在暂停期间运行.

如果没有活动图窗,或者非交互式后端在使用,这会执行 time.sleep(interval).

If there is no active figure, or if a non-interactive backend is in use, this executes time.sleep(interval).

注意

允许您与图形互动的事件循环仅在暂停期间运行.在计算过程中,您将无法与该图进行交互.如果计算需要很长时间(比如 0.5 秒或更长时间),交互会感觉滞后".在这种情况下,让计算在专用的工作线程或进程中运行可能是有意义的.

The event loop that allows you to interact with the figure only runs during the pause period. You will not be able to interact with the figure during computations. If the computations take a long time (say 0.5s or more) the interaction will feel "laggy". In that case it may make sense to let the computations run in a dedicated worker thread or process.

这篇关于与实时 matplotlib 图交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆