在matplotlib中绘制 pandas 日期 [英] Plot pandas dates in matplotlib
本文介绍了在matplotlib中绘制 pandas 日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含日期的固定宽度数据文件,但是当我尝试绘制数据时,日期在x轴上无法正常显示。
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.
我的文件看起来像
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
等
,我使用大熊猫阅读文件
#! /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()
所以我想这里的问题是从熊猫到matplotlib datetime的转换,怎么做一个转换?
So I suppose the issue here is conversion from pandas to matplotlib datetime, How would one do a conversion?
我也直接用熊猫尝试:
data.time = pd.to_datetime(data['time'], format='%Y-%m-%d %H:%M:%S.%f')
data.set_index('time') # Fails!!
data.time.plot()
但是这个失败了
TypeError: Empty 'Series': no numeric data to plot
感谢任何建议。
推荐答案
如果您使用包含列名称的列表)而不是一个字符串,data.set_index将工作
If you use a list containing the column name(s) instead of a string, data.set_index will work
以下内容应显示x轴上的日期:
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)
这篇关于在matplotlib中绘制 pandas 日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文