如何在python中使用matplotlib和pandas绘制CSV数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42372617/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to plot CSV data using matplotlib and pandas in python
提问by rushan
I have a python code in which I read a csv file using pandas and store date and time in one column Datetime. Now i want to plot Sensor Value on y-axis and datatime on x-axis. How can i achieve this? My code is below:
我有一个 python 代码,我在其中使用 pandas 读取一个 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)
Heres some rows from dataset:
这是数据集中的一些行:
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
回答by Rohan Sadale
Make sure your date column is in datetime format and use plot() function in matplotlib. You could do something similar to this. Here x-value will be your date column and y value will be sensor value.
确保您的日期列采用日期时间格式并在 matplotlib 中使用 plot() 函数。你可以做类似的东西这个。这里 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()