3

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.

  • Possible duplicate of [matplotlib intelligent axis labels for timedelta](http://stackoverflow.com/questions/15240003/matplotlib-intelligent-axis-labels-for-timedelta) – Suever Jan 06 '17 at 14:22

2 Answers2

7

You can convert your datetimeindex to a timedeltaindex and then plot.

df.index = df.index - df.index[0]
df.plot()
Ted Petrou
  • 59,042
  • 19
  • 131
  • 136
1

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()
Marjan Moderc
  • 2,747
  • 23
  • 44