问题描述
我想绘制一个数据框,它有一个 timedelta64 索引,索引在 x 轴上.
I want to plot a dataframe, which has a timedelta64 index with the index on the x-axis.
索引看起来像这样:
In [75]: test.index
Out[75]:
TimedeltaIndex([ '00:00:00', '00:00:00.020000', '00:00:00.040000',
'00:00:00.060000', '00:00:00.080000', '00:00:00.100000',
'00:00:00.120000', '00:00:00.140000', '00:00:00.160000',
'00:00:00.180000',
...
'07:29:31.660000', '07:29:31.680000', '07:29:31.700000',
'07:29:31.720000', '07:29:31.740000', '07:29:31.760000',
'07:29:31.780000', '07:29:31.800000', '07:29:31.820000',
'07:29:31.840000'],
dtype='timedelta64[ns]', name='master', length=923486, freq=None)
当我简单地绘制这个数据框时:
When I plot this dataframe simply with:
plt.plot(test)
我希望在x轴上获得timedeltaindex.然而,我只是在 x 轴上得到这个:
I would expect to get the timedeltaindex on the x-axis. However, instead I'm just getting this on the x-axis:
如何在 x 轴上获取我的 TimedeltaIndex?
How can I get my TimedeltaIndex on the x-axis instead?
推荐答案
首先你可以直接使用 pandas 来绘制数据.IE.代替 plt.plot(df)
,您可以使用
First of all you may use pandas directly to plot the data. I.e. instead of plt.plot(df)
you can use
df.plot()
这将在轴上显示正确的时间增量.
This would show the correct timedelta on the axis.
如果出于任何原因需要使用matplotlib进行绘图,例如因为时间戳记的间隔不相等,所以需要将 TimedeltaIndex
转换为绝对日期时间.选择一些(任意)开始,您可以将增量添加到开始以获得一些绝对日期时间.
If for any reason you need to use matplotlib for plotting, e.g. because you have unequally spaced timestamps, you need to convert the TimedeltaIndex
to an absolute datetime. Choosing some (arbitrary) start you may add the deltas to the start to get some absolute datetime.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
index = pd.to_timedelta(np.arange(50,100), unit='s')
df = pd.DataFrame(np.arange(50), index=index)
start=pd.Timestamp('20180606')
plt.plot(start+df.index, df)
plt.show()
这篇关于Matplotlib timedelta64索引作为x轴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!