xPunkt
xPunkt

Reputation: 55

Plotting timedelta vs. time in pandas

           Distance Speed   Heart Rate  Pace
Timestamp               
00:00:00    5.03    2.249   138 00:07:25
00:00:09    26.33   2.575   138 00:06:28
00:00:17    47.53   2.659   139 00:06:16
00:00:25    69.52   2.687   138 00:06:12

I have this Data Frame and I want to plot it using df.plot(subplots=True)

When I plot it Distance, Speed and Heart Rate get plotted but not the Pace. Types of the data if that helps:

Distance              float64
Speed                 float64
Heart Rate              int64
Pace          timedelta64[ns]
dtype: object

The problem seems to be that you can't plot a timedelta vs. time. How can I make this work?

Upvotes: 2

Views: 796

Answers (1)

IanS
IanS

Reputation: 16251

You could convert the pace to seconds:

df['Pace'] = df['Pace'].dt.total_seconds()

If you don't want to change the original column, you can assign it to a temporary dataframe:

df.assign(Pace=df['Pace'].dt.total_seconds()).plot(subplots=True)

Edit: In order to overwrite tick labels:

First, define a formatter function

import matplotlib.ticker as tkr
import datetime

def func(x, pos):
    return str(datetime.timedelta(seconds=x))
pace_format = tkr.FuncFormatter(func)

Second, apply it to your chart (I assume 'Pace' is in seconds):

ax = df['Pace'].plot()
ax.xaxis.set_major_formatter(pace_format);

When using subplots, you need to "reach" into the right ax object.

Upvotes: 2

Related Questions