matplotlib / seaborn 中的绘图持续时间

Plot duration in matplotlib / seaborn

我想用 matplotlibseaborn 在 Python 中绘制 5K 和 10K 运行 的结果。我的数据集有一个 time 列,其中包含 HH:MM:SS 格式的字符串对象,例如 00:28:501:17:23,以及比赛结果。 我通过计算以秒为单位的时间来创建我的图,但我更喜欢轴上 HH:MM:SS 格式的实际时间以便于阅读。

对此有什么建议吗?

到目前为止我的代码是(带有虚拟数据):

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

df = pd.DataFrame({'sex': ['M', 'M', 'M', 'M', 'F', 'F', 'F', 'F'], 'race': ['5K', '5K', '10K', '10K', '5K', '5K', '10K', '10K'], 'time': ['00:20:16', '00:24:57', '00:49:17', '00:56:10', '00:26:31', '00:33:06', '00:58:29', '01:05:03']})

df['time'] = pd.to_datetime(df['time'])
df['time_sec'] =[(t.hour * 3600 + t.minute * 60 + t.second) for t in df.time]
order=['5K', '10K']
palette = ['#3498db', '#ff0080']
fig, ax = plt.subplots(figsize=(16, 8))
sns.boxplot(ax=ax, data=df, x='time_sec', y='race', hue='sex', order=order, palette=palette, orient='h', linewidth=2.5)
plt.title('Time in seconds', fontsize=16)
plt.show()

您可以做的一件事是手动修改刻度:

order=['5K', '10K']
palette = ['#3498db', '#ff0080']
fig, ax = plt.subplots(figsize=(16, 8))
sns.boxplot(ax=ax, data=df, x='time_sec', y='race', hue='sex', order=order, palette=palette, orient='h', linewidth=2.5)

# get the ticks 
ticks = ax.get_xticks()

# convert the ticks to string
ax.set_xticklabels(pd.to_datetime(ticks, unit='s').strftime('%H:%M:%S'))

plt.title('Time in seconds', fontsize=16)

plt.show()

输出: