Interaction with live matplotlib schedule

I am trying to create a lively plot that updates as more data arrives.

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) 

The above code works. However, I cannot interact with the window created by plt.show()

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

+5
source share
1 answer

Use plt.pause() instead of time.sleep() .

The latter simply executes the main thread, and the GUI event loop does not start. Instead, plt.pause fires an event loop and allows you to interact with the shape.

From the documentation :

Pause for intervals of seconds.

If a shape is active, it will be updated and displayed, and the GUI event outline will work during pause.

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

Note

The event loop, which allows you to interact with the drawing, starts only during the pause period. You will not be able to interact with the figure during calculations. If the calculations take a lot of time (say, 0.5 s or more), the interaction will be felt "lags." In this case, it may make sense to allow calculations in a dedicated workflow or process.

+1
source

Source: https://habr.com/ru/post/1241843/


All Articles