我正在尝试创建一个实时绘图,该绘图会随着更多数据的可用而更新。
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()
如何在仍然能够与绘图窗口交互的同时绘制实时数据?
Use plt.pause()
代替time.sleep()
.
后者只是保持主线程的执行,GUI 事件循环不运行。反而,plt.pause
运行事件循环并允许您与人物交互。
来自文档 http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.pause:
暂停间隔秒。
如果有活动图形,它将被更新并显示,并且
GUI 事件循环将在暂停期间运行。
如果没有活动人物,或者如果有非交互式后端
使用,这会执行 time.sleep(interval)。
Note
允许您与图形交互的事件循环仅在暂停期间运行。在计算过程中您将无法与图形交互。如果计算需要很长时间(比如 0.5 秒或更长),交互就会感觉“滞后”。在这种情况下,让计算在专用的工作线程或进程中运行可能是有意义的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)