与活matplotlib图交互

Gur*_*sad 6 python matplotlib

我正在尝试创建一个更新数据的实时情节.

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)
Run Code Online (Sandbox Code Playgroud)

上面的代码有效.但是,我无法与生成的窗口进行交互plt.show()

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

kaz*_*ase 3

使用plt.pause()而不是time.sleep().

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

从文档中中:

暂停间隔秒。

如果有活动图形,它将被更新并显示,并且 GUI 事件循环将在暂停期间运行。

如果没有活动图形,或者正在使用非交互式后端,则执行 time.sleep(interval)。

笔记

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