Plot of pandas dates in matplotlib

I have a fixed-width data file containing dates, but when I try to plot data, the dates do not display properly on the X axis.

My files look 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 problem here is converting pandas to matplotlib datetime. How can the conversion be done?

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 it is not with

Type error: empty "series": no numerical data to build

+13
source share
1 answer

If you use a list containing a column name instead of a row, data.set_index will work

The following should be the dates along the 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) 
+20
source

Source: https://habr.com/ru/post/1200797/


All Articles