Issue
I have a fixed-width data file containing dates, but when I try to plot the data the dates are not displayed properly on the x-axis.
My files looks like
2014-07-10 11:49:14.377102 45
2014-07-10 11:50:14.449150 45
2014-07-10 11:51:14.521168 21
2014-07-10 11:52:14.574241 8
2014-07-10 11:53:14.646137 11
2014-07-10 11:54:14.717688 14
etc
and I use pandas to read in the file
#! /usr/bin/env python
import pandas as pd
import matplotlib.pyplot as plt
data = pd.read_fwf('myfile.log',header=None,names=['time','amount'],widths=[27,5])
data.time = pd.to_datetime(data['time'], format='%Y-%m-%d %H:%M:%S.%f')
plt.plot(data.time,data.amount)
plt.show()
So I suppose the issue here is conversion from pandas to matplotlib datetime, How would one do a conversion?
I also tried with pandas directly:
data.time = pd.to_datetime(data['time'], format='%Y-%m-%d %H:%M:%S.%f')
data.set_index('time') # Fails!!
data.time.plot()
but this fails with
TypeError: Empty 'Series': no numeric data to plot
Solution
If you use a list containing the column name(s) instead of a string, data.set_index will work
The following should show the dates on x-axis:
#! /usr/bin/env python
import pandas as pd
import matplotlib.pyplot as plt
data = pd.read_fwf('myfile.log',header=None,names=['time','amount'],widths=[27,5])
data.time = pd.to_datetime(data['time'], format='%Y-%m-%d %H:%M:%S.%f')
data.set_index(['time'],inplace=True)
data.plot()
#OR
plt.plot(data.index, data.amount)
Answered By - Osmond Bishop
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.