1 | initial version |
To update the plot window for pyplot using threading, you will need to:
Create a new thread to run your plot update function.
Inside your plot update function, you can call plt.ion() to turn on interactive mode, which allows you to update the plot dynamically.
Then, you can use plt.pause() to give the plot some time to update before continuing with the function.
Finally, use plt.draw() to redraw the plot with the updates made.
Here is an example code snippet:
import threading
import matplotlib.pyplot as plt
import random
def plot_update():
plt.ion() # turn on interactive mode
fig, ax = plt.subplots()
x_data = [0]
y_data = [random.randint(0, 100)] # random starting value
line, = ax.plot(x_data, y_data)
while True:
x_data.append(x_data[-1] + 1)
y_data.append(random.randint(0, 100)) # generate new y value
line.set_xdata(x_data)
line.set_ydata(y_data)
ax.relim()
ax.autoscale_view()
plt.draw()
plt.pause(0.1) # wait for 0.1 seconds before continuing the loop
thread = threading.Thread(target=plot_update)
thread.start()
In this example, a new thread is created to execute the plot_update function, which generates random y data every 0.1 seconds and updates the plot window. The plt.pause() function pauses the thread for 0.1 seconds to allow the plot to update before continuing with the loop. The plt.draw() function redraws the plot with the updated data.