2014-07-17 62 views
2

繪製與Python數據我有來自傳感器幾乎5萬條數據線連接到一個樹莓派的文本文件。它看起來是這樣的:如何從文本文件

2014-07-16 15:57:35.536579, 128, 251, 254, 255, 30.062 
2014-07-16 15:57:37.763030, 132, 252, 250, 255, 30.062 
2014-07-16 15:57:39.993090, 135, 249, 239, 255, 30.125 
2014-07-16 15:57:42.224499, 142, 251, 221, 255, 30.125 
2014-07-16 15:57:44.452908, 152, 252, 199, 255, 30.187 
2014-07-16 15:57:46.683009, 162, 246, 189, 255, 30.187 

所以基本上(從左至右)的日期和時間,傳感器1,傳感器2,傳感器3,傳感器4,傳感器5.我想繪製此通過使用Python,伊夫閱讀matplotlib繪製圖表。但是如何從文本文件中繪製這些數據呢?我想在x軸上繪製時間戳,並在y軸上繪製來自一個圖表中不同傳感器的數據。我在matplotlib中根本沒有經驗。

對於閱讀的文本文件,我是這樣想的東西:

line = file.readlines() 
new_line = line.strip(", ") 
date = new_line[0] 
sensor1 = new_line[1] 
#and so on 
+0

的gnuplot可以直接做到這一點。從gnuplot裏面:'set timefmt'%Y-%m-%d%H:%M:%S「;設置xdata時間;使用1:2'繪製't.gp' –

回答

1

如果你不想安裝pandas,「純NumPy的」解決方案是使用`

import numpy as np 
import datetime 

# date field conversion function 
dateconv = lambda s: datetime.strptime(s, '%Y-%M-%D %H:%M:%S:.%f') 

col_names = ["Timestamp", "val1", "val2", "val3", "val4", "val5"] 
dtypes = ["object", "uint8", "uint8", "uint8", "uint8", "float"] 
mydata = np.genfromtxt("myfile.csv", delimiter=',', names=col_names, dtype=dtypes, converters={"Time": dateconv}) 

此內容後的mydata

array([('2014-07-16 15:57:35.536579', 128, 251, 254, 255, 30.062), 
     ('2014-07-16 15:57:37.763030', 132, 252, 250, 255, 30.062), 
     ('2014-07-16 15:57:39.993090', 135, 249, 239, 255, 30.125), 
     ('2014-07-16 15:57:42.224499', 142, 251, 221, 255, 30.125), 
     ('2014-07-16 15:57:44.452908', 152, 252, 199, 255, 30.187), 
     ('2014-07-16 15:57:46.683009', 162, 246, 189, 255, 30.187)], 
     dtype=[('Timestamp', 'O'), ('val1', 'u1'), ('val2', 'u1'), ('val3', 'u1'), ('val4', 'u1'), ('val5', '<f8')]) 

現在你可以嘗試,如mydata['val5']

array([ 30.062, 30.062, 30.125, 30.125, 30.187, 30.187]) 

datetime.datetime對象現在存儲爲對象。其他一切都與您指定的數據類型一起存儲。

2

我建議使用大熊貓(類似於至R的東西)。 Supppose您的輸入樣本是在文件「data.csv」:

import pandas as pd 
df = pd.read_csv('data.csv', parse_dates=True,index_col=0, 
     names = ['timestamp','x','y','z','w','k']) 
df.plot()