matplotlib / seaborn中的情节持续时间

时间:2019-06-09 14:39:49

标签: python datetime matplotlib seaborn duration

我想绘制使用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()

enter image description here

1 个答案:

答案 0 :(得分:1)

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

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()

输出:

enter image description here