0

I am struggling with pyplot from the matlpotlib library. My goal is to add new point to the plot when Enter is pressed. Also I want plot to be interactive. To detect if Enter is pressed I've creted while True loop in function in other thread. As it is now, new points shows up, but plot window freezes. The same thing happens if "input()" is repleaced by "time.sleep(10)". I want everything to run smoothly. Any ideas? Code below.

import random
import threading
import time
import matplotlib.pyplot as plt

plt.ion()
figure = plt.figure()
ax = figure.gca()

x = []
y = []
line1, = ax.plot(x, y, 'o')


def generate_new_point():
    input("Press enter to generate new point")
    x_new = random.randint(0, 10)
    y_new = random.randint(-20, 20)
    return x_new, y_new


x_generated = 0
y_generated = 0
point_generated = False


def thread_function():
    global x_generated, y_generated, point_generated
    while True:
        x_generated, y_generated = generate_new_point()
        point_generated = True
        # if new point is generated in thread_function then I want to update my plot


thread1 = threading.Thread(target=thread_function, args=())
thread1.start()
while True:
    if point_generated:
        x.append(x_generated)
        y.append(y_generated)

        line1.set_xdata(x)
        line1.set_ydata(y)
        ax.relim()      # to rescale axis
        ax.autoscale()

        figure.canvas.draw()
        figure.canvas.flush_events()
        time.sleep(0.01)
        point_generated = False    # wait for user to press enter again
PLdzik
  • 1
  • 1

0 Answers0