使用日期索引的时间序列数据在x轴上绘制经过的时间。

3

在我的pandas数据框中,我的时间序列数据是按绝对时间索引的(格式为YYYY-MM-DD HH24:MI:SS.nnnnn):

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”)的递增值?我需要使用Period或使用asfreq()将其转换为频率吗?还是应该使用DateFormatter?
文档有点混乱,并且似乎没有好的例子 - 大多数时间序列示例似乎都围绕着如月份或年份等粗略间隔展开。

可能是matplotlib为时间差智能生成坐标轴标签的重复问题。 - Suever
2个回答

7
您可以将您的datetimeindex转换为timedeltaindex,然后进行绘制。
df.index = df.index - df.index[0]
df.plot()

谢谢!真不敢相信这竟然如此简单! - user1612443
2
如果需要绘制秒数的话,我会使用TimeDeltaIndex的seconds属性 - (df.index-df.index[0]).seconds - Nickil Maveli

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()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接