Home > OS >  set time interval on a line plot axis
set time interval on a line plot axis

Time:09-26

Here is my time series df:

df = pd.DataFrame({'session_id': [6,6,6,6,7,7,7],
 'timestamp': ['2016-04-01 08:00:00','2016-04-01 08:40:05','2016-04-01 09:35:10','2016-04-01 10:24:15',
               '2016-04-01 01:40:10','2016-04-01 02:20:13','2016-04-01 02:55:20'],
 'speed': [26.8551,27.673,18.0626,21.4778,17.6581,24.4941,14.42]
 })

df
    session_id  timestamp            speed
0      6       2016-04-01 08:00:00  26.8551
1      6       2016-04-01 08:40:05  27.6730
2      6       2016-04-01 09:35:10  18.0626
3      6       2016-04-01 10:24:15  21.4778
4      7       2016-04-01 01:40:10  17.6581
5      7       2016-04-01 02:20:13  24.4941
6      7       2016-04-01 02:55:20  14.4200

And I plot the speed against timestamp like so:

df['timestamp'] = pd.to_datetime(df['timestamp'], format='%Y-%m-%d %H:%M:%S').dt.strftime('%H:%M:%S')
seaborn.lineplot(data=df, x='timestamp', y='speed', hue='session_id')

enter image description here

How do I set the x-axis scale to be an an interval of 30 minutes?

CodePudding user response:

To do what you are looking for, firstly keep the axis data in dateime itself - don't change it to str (strftime). Then you can use MinuteLocator and set the times to show 0 and 30 min ticks only. Use DateFormatter so that the shown ticklables are in the %H:%M format. Note that session_id of 7 is now earlier than 6. If you don't want the ticks at an angle, comment out the last line You can use below code...

df = pd.DataFrame({'session_id': [6,6,6,6,7,7,7],
 'timestamp': ['2016-04-01 08:00:00','2016-04-01 08:40:05','2016-04-01 09:35:10','2016-04-01 10:24:15',
               '2016-04-01 01:40:10','2016-04-01 02:20:13','2016-04-01 02:55:20'],
 'speed': [26.8551,27.673,18.0626,21.4778,17.6581,24.4941,14.42]
 })

df['timestamp'] = pd.to_datetime(df['timestamp'], format='%Y-%m-%d %H:%M:%S')#.dt.strftime('%H:%M:%S')

fig, ax=plt.subplots(figsize=(12,5))
sns.lineplot(data=df, x='timestamp', y='speed', hue='session_id')

from matplotlib import dates as mdates
xformatter = mdates.DateFormatter('%H:%M')
xlocator = mdates.MinuteLocator(byminute=[0,30], interval = 1) ##Set ticks to show 00 and 30 minutes only

## Set xtick labels to appear every 30 minutes
ax.xaxis.set_major_locator(xlocator)

## Format xtick labels as HH:MM
ax.xaxis.set_major_formatter(xformatter)
fig.autofmt_xdate()

enter image description here

  • Related