rushan
rushan

Reputation: 221

How to plot data from csv for specific date and time using matplotlib?

I have written a python program to get data from csv using pandas and plot the data using matplotlib. My code is below with result:

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

#f = plt.figure(figsize=(10, 10))
df.plot(x='Datetime',y='Sensor Value',) # figure.gca means "get current axis"
plt.title('Title here!', color='black')
plt.tight_layout()
plt._show()

enter image description here

Now as you can see the x-axis looks horrible. How can I plot the x-axis for a single date and time interval so that it does not looks like overlapping each other? I have stored both date and time as one column in my dataframe.

My Dataframe looks like this:

                       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

Upvotes: 1

Views: 13052

Answers (1)

Sebastian Wozny
Sebastian Wozny

Reputation: 17526

Hacky way

Try this:

import pylab as pl
pl.xticks(rotation = 90)

It will rotate the labels by 90 degrees, thus eliminating overlap.

Cleaner way

Check out this link which describes how to use fig.autofmt_xdate() and let matplotlib pick the best way to format your dates.

Pandas way

Use to_datetime() and set_index with DataFrame.plot():

df.Datetime=pd.to_datetime(df.Datetime)
df.set_index('Datetime')
df['Sensor Value'].plot()

pandas will then take care to plot it nicely for you:

enter image description here

my Dataframe looks like this:

                      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

Upvotes: 4

Related Questions