sss
sss

Reputation: 59

Plotting Real Time Data in Python

I wrote a script that generates random coordinates and writes them into a text file with no formatting.

Is there a way to format this list so it is easier to read? Like (x, y) per line? Right now it is a list with a single space between them.

Is there an easier way to generate random coordinates in one python file without the use of a text file? Or is it easier to use a text file?

Below is the working code for this and an example of the text file: (Revised based on commentary and working)

import random
import threading

def main():

    #Open a file named numbersmake.txt.
    outfile = open('new.txt', 'w')

    for count in range(12000):
        x = random.randint(0,10000)
        y = random.randint(0,10000)
        outfile.write("{},{}\n".format(x, y))

    #Close the file.
    outfile.close()
    print('The data is now the the new.txt file')

def coordinate():
    threading.Timer(0.0000000000001, coordinate).start ()

coordinate()

#Call the main function
main()

I have tried split and does not work. I know I don't need the threading option. I would rather have the threading over the range but the range is okay for now...

Example of the text in text file: [4308][1461][1163][846][1532][318]... and so on


I wrote a python script that reads the text file of coordinates and places them on a graph, however, no points are being plotted. The graph itself does show. Below is the code: (Revised based on commentary)

import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
from numpy import loadtxt

style.use('dark_background')

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

with open('new.txt') as graph_data:
    for line in graph_data:
        x, y = line.split(',') 

def animate(i):
    xs = []
    ys = []
    for line in graph_data:
        if len(line)>1:
            x,y = line.split(',')
            xs.append(x)
            ys.append(y)

    ax1.clear()
    ax1.plot(xs,ys)

lines = loadtxt("C:\\Users\\591756\\new.txt", comments="#", delimiter=",", unpack="false")
ani = animation.FuncAnimation(fig, animate, interval=1000) # 1 second- 10000 milliseconds
plt.show()

Upvotes: 2

Views: 2200

Answers (1)

OneCricketeer
OneCricketeer

Reputation: 191914

In order for the logic of your plotting to even work, the file should be written like so

with open('new.txt', 'w') as out_file:
    for count in range(12000):
        x = random.randint(0,10000)
        y = random.randint(0,10000)
        outfile.write("{},{}\n".format(x, y))

Also, you read lines like this

def animate(i):
    xs = []
    ys = []
    with open('filename') as graph_data:
        for line in graph_data:
            x, y = line.split(',') 
            xs.append(x)
            ys.append(y)
    ax1.clear()
    ax1.plot(xs,ys)

Upvotes: 3

Related Questions