Interacting with live matplotlib plot

2024/9/16 23:17:03

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

import os,sys
import matplotlib.pyplot as pltimport time
import randomdef 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 beyondwhile 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'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?

Answer

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

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.

From the documentation:

Pause for interval seconds.

If there is an active figure it will be updated and displayed, and theGUI event loop will run during the pause.

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

Note

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.

https://en.xdnf.cn/q/72724.html

Related Q&A

pandas groupby: can I select an agg function by one level of a column MultiIndex?

I have a pandas DataFrame with a MultiIndex of columns:columns=pd.MultiIndex.from_tuples([(c, i) for c in [a, b] for i in range(3)]) df = pd.DataFrame(np.random.randn(4, 6),index=[0, 0, 1, 1],columns=c…

Bottle web app not serving static css files

My bottle web application is not serving my main.css file despite the fact I am using the static_file method.app.pyfrom bottle import * from xml.dom import minidom @route(/) def index():return template…

How to wrap text in OpenCV when I print it on an image and it exceeds the frame of the image?

I have a 1:1 ratio image and I want to make sure that if the text exceeds the frame of the image, it gets wrapped to the next line. How would I do it?I am thinking of doing an if-else block, where &qu…

pandas series filtering between values

If s is a pandas.Series, I know I can do this:b = s < 4or b = s > 0but I cant dob = 0 < s < 4orb = (0 < s) and (s < 4)What is the idiomatic pandas method for creating a boolean series…

python os.path.exists reports False when files is there

Hi have an application which is sometimes reporting that a file does not exist even when it does, I am using os.path.exists and the file is on a mounted network share. I am on OSX Yosemite, python 2.7.…

Python unhashable type: numpy.ndarray

I worked on making functions for K Nearest Neighbors. I have tested each function separately and they all work well. However whenever I put them together and run KNN_method, it shows unhashable type: n…

Efficient way to generate Lime explanations for full dataset

Am working on a binary classification problem with 1000 rows and 15 features. Currently am using Lime to explain the predictions of each instance. I use the below code to generate explanations for full…

how to handle javascript alerts in selenium using python

So I there is this button I want to click and if its the first time youve clicked it. A javascript alert popup will appear. Ive been using firebug and just cant find where that javascript is located an…

testing.postgresql command not found: initdb inside docker

Hi im trying to make a unittest with postgresql database that use sqlalchemy and alembicAlso im running it on docker postgresqlIm following the docs of testing.postgresql(docs) to set up a temporary po…

Recommended approach for loading CouchDB design documents in Python?

Im very new to couch, but Im trying to use it on a new Python project, and Id like to use python to write the design documents (views), also. Ive already configured Couch to use the couchpy view server…