Ask Your Question
1

How can the plot window for pyplot be updated using threading?

asked 2023-05-23 06:38:05 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-05-23 06:50:02 +0000

scrum gravatar image

To update the plot window for pyplot using threading, you will need to:

  1. Create a new thread to run your plot update function.

  2. Inside your plot update function, you can call plt.ion() to turn on interactive mode, which allows you to update the plot dynamically.

  3. Then, you can use plt.pause() to give the plot some time to update before continuing with the function.

  4. 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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-23 06:38:05 +0000

Seen: 12 times

Last updated: May 23 '23