[英]Plot duration in matplotlib / seaborn
我想绘制使用matplotlib
和seaborn
在Python中运行的5K和10K的结果。 我的数据集有一个列time
,其中包含HH:MM:SS
格式的字符串对象,例如00:28:50
或1: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()
输出:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.