Reputation: 221
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:
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
Upvotes: 13
Views: 91679
Reputation: 29
Updated solution for Python 3.9 with date in the format '2022-01-11 23:57' :
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('data.csv')
df['Datetime'] = pd.to_datetime(df['Datetime'], format='%m/%d/%Y %H:%M')
# plot the dataframe directly
ax = df.plot(x='Datetime', y='Sensor Value')
# beautify the x-labels
ax.autofmt_xdate()
plt.show()
Or plot with pyplot
directly
fig, ax = plt.subplots()
ax.plt('Datetime', 'Sensor Value', data=df)
ax.autofmt_xdate()
Upvotes: 1
Reputation: 1
To get this code to work on the machine I'm currently coding on (MacOS 10.14) with Python 2.7.16, I needed to declare the row of the CSV file that the headers are on. So this is a header=1
in the read_csv section, as is recommended on the official pandas read_csv page here .
My code is below:
import pandas as pd
from datetime import datetime
import csv
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
headers = ['sensor_data','Date']
df = pd.read_csv('output.csv',header=1,names=headers)
df['Date']= pd.to_datetime(df['Date'], format='%Y-%m-%d %H:%M:%S')
df['Date']= df['Date'].map(lambda x: datetime.strptime(str(x), '%Y-%m-%d %H:%M:%S'))
x = df['Date']
print(x)
y = df['sensor_data']
# plot
plt.plot(x,y)
# beautify the x-labels
plt.gcf().autofmt_xdate()
plt.show()
Upvotes: 0
Reputation: 5431
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.
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()
Upvotes: 27