Matplotlib timedelta64 index as x-axis

社会主义新天地 提交于 2020-01-14 19:05:25

问题


I want to plot a dataframe, which has a timedelta64 index with the index on the x-axis.

The index looks like this:

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)

I would expect to get the timedeltaindex on the x-axis. However, instead I'm just getting this on the x-axis:

How can I get my TimedeltaIndex on the x-axis instead?


回答1:


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.

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


来源:https://stackoverflow.com/questions/50717534/matplotlib-timedelta64-index-as-x-axis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!