将日期/时间和数据从csv中提取到matplotlib中 [英] Getting date/time and data out of csv into matplotlib
问题描述
我的最终目标是从csv日志文件中获取matplotlib绘制的日期/时间和温度数据,数据格式如下:
日期/时间,temp1,temp2,temp3,temp4等
2017年8月25日14:55:49,20.851,20.953,21.025,21.055,ect
8/25/2017 14 :56:49,20.799,20.944,20.99,21.029,ect
我正试图拔角数据集作为本示例的起点:$ b $ b
My end goal is to get date/time and temp data plotted by matplotlib from a csv logfile, data is formatted as such:
date/time,temp1,temp2,temp3,temp4,ect
8/25/2017 14:55:49,20.851,20.953,21.025,21.055,ect
8/25/2017 14:56:49,20.799,20.944,20.99,21.029,ect
I'm trying to shoehorn my dataset into this example as a starting point: https://matplotlib.org/gallery/api/date.html
As I'm still getting familiar with matplotlib, I'm not sure what the preferred inputs are, the above example uses arrays, so if that is the best option than my question is what's an efficient way to get this data into a properly formatted array? Here is my code which I got as far as reading one line of data and figuring out how to parse out the date/time and putting into a datetime container:
import datetime
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.cbook as cbook
f = open(r'Sample Data.csv')
#Burn off top crap of logfile
for x in range(38):
f.readline()
#Headers
pantsHeaders = f.readline()
#Start of data
pants1 = f.readline().replace('\x00','').strip('\n').split(',')
pantsDate = datetime.date(int(pants1[0].split(' ')[0].split('/')[2]),int(pants1[0].split(' ')[0].split('/')[0]),int(pants1[0].split(' ')[0].split('/')[1]))
pantsTime = datetime.time(int(pants1[0].split(' ')[1].split(':')[0]),int(pants1[0].split(' ')[1].split(':')[1]),int(pants1[0].split(' ')[1].split(':')[2]))
date = datetime.datetime.combine(pantsDate, pantsTime)
There has got to be a better way to parse out the date/time info than how I'm doing it, and I'm open to any approach to get a matplotlib friendly format (arrays or otherwise).
Pandas is good at handling datetime formats, and it's integrated nicely with Matplotlib.
For example, with your example data:
datetime,temp1,temp2,temp3,temp4
8/25/2017 14:55:49,20.851,20.953,21.025,21.055
8/25/2017 14:56:49,20.799,20.944,20.99,21.029
If that's saved as example.csv
, you can do:
import pandas as pd
df = pd.read_csv("example.csv", parse_dates=['datetime'], index_col="datetime")
df.plot()
这篇关于将日期/时间和数据从csv中提取到matplotlib中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!