0

I'm trying to update a graph in real time from an updating .txt Notepad++ file. In other words, random numbers are printed to the text file, then the python script reads the numbers from the text file and plots it.

I assumed that Multi-threading would be required so the two functions can run at the same time. I'm using the schedule module so I can print random numbers onto the text file every 3 seconds. Here is my code:

import random
import schedule
import time
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from threading import Thread

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)


def gen_text():
    num1 = random.randint(1, 100)
    num2 = random.randint(1, 100)
    print(str(num1) + ',' + str(num2), file=open('TEXT FILE', 'a'))

schedule.every(3).seconds.do(gen_text)
pull_data = open('TEXT FILE', 'r').read()


def animate(i):
    data_array = pull_data.split('\n')
    xar = []
    yar = []
    for each_line in data_array:
        if len(each_line) > 1:
            x, y = each_line.split(',')
            xar.append(int(x))
            yar.append(int(y))
    ax.clear()
    ax.plot(xar, yar)

if __name__ == '__main__':
    Thread(target=animate).start()
    Thread(target=gen_text).start()
    ani = animation.FuncAnimation(fig, animate, interval=3000)
    plt.show()


while True:
    schedule.run_pending()
    for line in pull_data:
        Type = line.split(",")
        x = Type[0]
        y = Type[1]
        print(x, y)

This code just shows a Matplotlib graph with lines plotted from previous runs of the code. Not an updating real-time one. Is multi-threading the correct approach? If not, then how could I solve this?

SK-logic
  • 9,605
  • 1
  • 23
  • 35
Star Man
  • 171
  • 1
  • 2
  • 11
  • First you should fix the `schedule` code so that it works properly. – user202729 Jan 31 '21 at 05:01
  • 1
    About interactive: You need https://matplotlib.org/3.3.3/users/interactive.html too (can't find a stack question for that, but it's already in the dominantation...). – user202729 Jan 31 '21 at 05:01

0 Answers0