如何使用 Python 从文本文件中绘制数据 [英] How to plot data with Python from text file

查看:37
本文介绍了如何使用 Python 从文本文件中绘制数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文件,其中包含来自连接到树莓派的传感器的近 5 万行数据.它看起来像这样:

I have a text file with almost 50k lines of data from sensors that are connected to a raspberry pi. It looks something like this:

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的经验.

So basically (from left to right) date and time, sensor 1, sensor 2, sensor 3, sensor 4, sensor 5. I want to plot this by using Python, Ive read about matplotlib for plotting graphs. But how can I plot this data from a text file? I would like to plot on the x axis the timestamps and on the y axis the data from different sensors in one chart. Im not experienced in matplotlib at all.

为了阅读文本文件,我想到了这样的事情:

For reading the text file I was thinking of something like this:

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

推荐答案

如果不想安装pandas,纯NumPy"的解决方案是使用`

If you do not want to install pandas, the "pure NumPy" solution is to use `

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 对象现在存储为对象.其他所有内容都使用您指定的数据类型存储.

The datetime.datetime objects are now stored as objects. Everything else is stored with the datatype you have specified.

这篇关于如何使用 Python 从文本文件中绘制数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆