'Plot elapsed time on x axis using date indexed time-series data
In my pandas dataframe, my time series data is indexed by absolute time (a date of format 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
How can I plot this data such that the x-axis of my plots is an increasing value of some interval of seconds (e.g, "0 10 20 30 40 50") relative to the timestamp of my first sample ? Do I need to use a Period, or convert to a frequency using asfreq() ? Or should I be using a DateFormatter ?
The documentation is a bit confusing and there don't seem to be any good examples - most of the time series examples seem to revolve around coarse intervals such as months or years.
Solution 1:[1]
You can convert your datetimeindex to a timedeltaindex and then plot.
df.index = df.index - df.index[0]
df.plot()
Solution 2:[2]
There might be a built-in method to do this, but what you want can be achieved by substracting datetimes within list comprehension and using 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()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ted Petrou |
Solution 2 |