【问题标题】:Plot duration in matplotlib / seabornmatplotlib / seaborn 中的绘图持续时间
【发布时间】:2019-10-24 05:05:50
【问题描述】:

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

【问题讨论】:

    标签: python datetime matplotlib seaborn duration


    【解决方案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()
    

    输出:

    【讨论】:

      猜你喜欢
      • 2014-03-27
      • 2013-07-25
      • 1970-01-01
      • 2021-05-12
      • 2018-11-23
      • 2021-03-31
      • 1970-01-01
      • 2017-11-24
      相关资源
      最近更新 更多