[英]set time interval on a line plot axis
Here is my time series df
:这是我的时间序列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:我 plot 对时间戳的速度如下:
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')
How do I set the x-axis scale to be an an interval of 30 minutes?如何将 x 轴刻度设置为 30 分钟的间隔?
To do what you are looking for, firstly keep the axis data in dateime itself - don't change it to str (strftime).要执行您要查找的操作,首先将轴数据保存在 datetime 本身中 - 不要将其更改为 str (strftime)。 Then you can use MinuteLocator and set the times to show 0 and 30 min ticks only.然后您可以使用 MinuteLocator 并将时间设置为仅显示 0 和 30 分钟刻度。 Use DateFormatter so that the shown ticklables are in the %H:%M format.使用 DateFormatter 以使显示的 ticklables 采用 %H:%M 格式。 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...请注意,7 的 session_id 现在早于 6。如果您不希望刻度线倾斜,请注释掉最后一行您可以使用下面的代码...
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.