2017-01-06 40 views
1

在我的熊猫数据框中,我的时间序列数据按绝对时间(格式为YYYY-MM-DD HH24:MI:SS.nnnnn的日期)编制索引:使用日期索引时间序列数据在x轴上绘制经过时间

2017-01-04 16:25:25.143493 58 
2017-01-04 16:25:26.145494 62 
2017-01-04 16:25:27.147495 57 
2017-01-04 16:25:28.149496 51 
2017-01-04 16:25:29.151497 61 

我该如何绘制这些数据,使得我的图的x轴相对于我的第一个样本的时间戳是某个时间间隔(例如,“0 10 20 30 40 50”)的递增值?我需要使用句点,还是使用asfreq()转换为频率?或者我应该使用DateFormatter?

该文档有点混乱,似乎没有任何好的例子 - 大多数时间序列的例子似乎围绕粗略的间隔,如几个月或几年。

+0

[matplotlib智能轴标签timedelta]的可能的复制(http://stackoverflow.com/questions/15240003/matplotlib-intelligent-axis-labels-for-timedelta) – Suever

回答

3

您可以将datetimeindex转换为timedeltaindex,然后情节。

df.index = df.index - df.index[0] 
df.plot() 
+0

谢谢!不能相信这很简单! – user1612443

+0

如果绘制秒数是有意义的,那么我会使用'TimeDeltaIndex'的秒属性 - '(df.index - df.index [0])。seconds' –

1

可能有一个内置的方法来做到这一点,但你要可以通过减去列表理解中的日期时间和使用total_seconds()达到什么:

# Generate a random timeseries 
a = pd.Series(index=pd.date_range("20000101",freq="s",periods=50),data=np.random.randint(0,10,50)) 

# Create a new index by calculating relative difference between the datetimes. 
# If you use total_seconds, you will convert datetimes into integers (which is what you wanted in your question) 
new_index = [(i-a.index[0]) for i in a.index] 

# Apply new index to the original Series 
a.index = new_index 

# plot the data 
a.plot() 
相关问题