2017-06-08 18 views
2

ランダム座標を生成し、フォーマットなしのテキストファイルに書き込むスクリプトを作成しました。Pythonでリアルタイムデータをプロットする

読みやすいようにこのリストをフォーマットする方法はありますか? 1行に(x、y)のように?今、それはそれらの間に単一のスペースを持つリストです。

テキストファイルを使用せずに1つの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() 

(解説と作業に基づいて改訂します)。私はスレッドオプションが必要ないことを知っています。私はしかし、座標のテキストファイルを読み込み、グラフ上にそれらを置くPythonスクリプトを書いた私はむしろ範囲を超えるスレッドを持っているだろうが、範囲は今...

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


のために大丈夫です、点はプロットされません。グラフそのものが表示されます。以下のコードは次のとおりです。

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

改行文字をファイルまたは他の区切り文字に手動で書き込む必要があります。しかし、pickleモジュールやjsonモジュールはより良いアプローチになります –

+1

'split( '、')'はデータにカンマなしでは機能しないので、ポイントがプロットされないことがありますか? –

+1

素晴らしい!テキストファイルはBEAUTIFULのように見えます。手伝ってくれてどうもありがとう!私はすべての編集を完了し、値を引き上げているスクリプトに追加しましたが、「ValueError:閉じたファイルに対する入出力操作」というエラーメッセージが表示されました。 – sss

答えて

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) 
関連する問題