用Python绘制实时数据

时间:2017-06-08 12:21:47

标签: python python-3.x animation graph real-time

我写了一个生成随机坐标的脚本,并将它们写入没有格式化的文本文件中。

有没有办法格式化这个列表,以便更容易阅读?像每行(x,y)?现在它是一个列表,它们之间有一个空格。

有没有更简单的方法在一个python文件中生成随机坐标而不使用文本文件?或者使用文本文件更容易?

以下是此工作代码和文本文件示例:(根据评论和工作进行修订)

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()

我尝试过拆分并且不起作用。我知道我不需要线程选项。我宁愿在范围内进行穿线,但现在范围还可以......

  

文本文件中的文本示例:   [1461] [1163] [846] [1532] [318] ......等等

我写了一个python脚本,它读取坐标的文本文件并将它们放在图表上,但是,没有绘制点。图表本身确实显示出来。以下是代码:(基于评论修订)

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()

1 个答案:

答案 0 :(得分:2)

为了使绘图的逻辑均匀工作,文件应该像这样编写

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))

另外,你读这样的行

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)