如何在python中使用matplotlib和pandas绘制CSV数据

问题描述 投票:4回答:1

我有一个python代码,在其中我使用熊猫读取了一个csv文件,并将日期和时间存储在一列Datetime中。现在,我想在y轴上绘制传感器值,在x轴上绘制数据时间。我怎样才能做到这一点?我的代码如下:

import pandas as pd
import datetime
import csv
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
headers = ['Sensor Value','Date','Time']
df = pd.read_csv('C:/Users\Lala Rushan\Downloads\DataLog.CSV',parse_dates=     {"Datetime" : [1,2]},names=headers)
print (df)

这里有一些数据集的行:

                      Datetime  Sensor Value
0     2017/02/17  19:06:17.188             2
1     2017/02/17  19:06:22.360            72
2     2017/02/17  19:06:27.348            72
3     2017/02/17  19:06:32.482            72
4     2017/02/17  19:06:37.515            74
5     2017/02/17  19:06:42.580            70
6     2017/02/17  19:06:47.660            72
python csv pandas matplotlib
1个回答
11
投票

请确保您的日期列为日期时间格式,并在matplotlib中使用plot()函数。您可以执行类似于this的操作。这里的x值将是您的日期列,而y值将是传感器值。

import pandas as pd
from datetime import datetime
import csv
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
headers = ['Sensor Value','Date','Time']
df = pd.read_csv('C:/Users\Lala Rushan\Downloads\DataLog.CSV',names=headers)
print (df)

df['Date'] = df['Date'].map(lambda x: datetime.strptime(str(x), '%Y/%m/%d %H:%M:%S.%f'))
x = df['Date']
y = df['Sensor Value']

# plot
plt.plot(x,y)
# beautify the x-labels
plt.gcf().autofmt_xdate()

plt.show()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.