I want to plot the results of a 5K and a 10K run in Python with matplotlib
and seaborn
. My dataset has a column time
that contains a string object in a HH:MM:SS
format, like 00:28:50
or 1:17:23
, with the race results. I created my plot by calculating the time in seconds, but I prefer the actual time in HH:MM:SS
format on the axis for readability.
Any suggestions to to do this?
My code so far is (with dummy data):
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()
One thing you could do is to modify the ticks manually:
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()
Output:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.