2016-01-29 29 views
5

我试图创建生动的情节,其更新为可用的数据交互。现场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) 

上述代码有效。然而,我无法与plt.show()

产生窗口交互我如何可以绘制实时的数据,同时还能够与绘图窗口进行交互?

回答

1

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

后者简单地保持主线程的执行和GUI事件循环不运行。相反,plt.pause运行事件循环,并允许您与人物进行交互。

documentation

暂停区间秒。

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

如果没有活动数字,或者如果非交互式后端处于 使用中,则执行time.sleep(interval)。

事件循环,使您可以用图形交互仅在中止期间运行。在计算过程中,您将无法与数字交互。如果计算需要很长的时间(比如0.5秒或更多)的相互作用会觉得“laggy”。在这种情况下,让计算在专用的工作线程或进程中运行可能是有意义的。

+0

我很困惑..如果循环仅在'plt.pause()'期间运行,那么我不必指定一个大的暂停时间段来确保它可以接收和处理所有的命令鼠标拖动 - 拉伸/缩放/等)?你能修改我的例子来描述你的意思吗? –

+0

让你的例子就像现在一样,用'plt.pause(0.3)'替换'time.sleep(0.3)'。你不需要很长的停顿时间,因为你有一个短暂的停顿时间,无休止地继续。如果你的代码在暂停命令之间花费的时间很少,那么一切都应该平稳运行。 – kazemakase