【问题标题】:Format pandas y axis to show time instead of total seconds格式化 pandas y 轴以显示时间而不是总秒数
【发布时间】:2018-09-27 13:18:40
【问题描述】:

我在数据框中进行了测量。列是不同的对象。索引是一个 datetime64 索引。现在,对于每个日期,我都有每列的总秒数 (int) 测量值。

一切都很好,我唯一的问题不是在 y 轴上显示 6000 秒,而是我想显示 1:40 来表示 1 小时 40 分钟。

我怎样才能真正做到这一点?

day         Object1  Object2
2017-01-01     6000     1234

我想要

day         Object1  Object2
2017-01-01  1:40:00  00:20:34 

你能告诉我怎么做吗

【问题讨论】:

    标签: python pandas matplotlib label duration


    【解决方案1】:

    这是可能的,但本机尚不支持ploting timedelta

    df['Object1'] = pd.to_timedelta(df['Object1'], unit='s')
    df['Object2'] = pd.to_timedelta(df['Object2'], unit='s')
    

    或者:

    cols = ['Object1', 'Object2']
    df[cols] = df[cols].apply(lambda x: pd.to_timedelta(x, unit='s'))
    

    print (df)
              day  Object1  Object2
    0  2017-01-01 01:40:00 00:20:34
    

    但是FuncFormatter可以吗:

    df = pd.DataFrame({'Object1': [6000, 4000, 3000], 'Object2':[3000,5000,2110]})
    
    import matplotlib.ticker as tkr
    import datetime
    
    def func(x, pos):
        return str(datetime.timedelta(seconds=x))
    fmt = tkr.FuncFormatter(func)
    
    
    ax = df.plot(x='Object1', y='Object2', rot=90)
    ax.xaxis.set_major_formatter(fmt)
    ax.yaxis.set_major_formatter(fmt)
    

    【讨论】:

    • 提及 绘图 timedelta 尚不支持,绝对值得很多赞:-)
    • 这绝对有帮助。现在是否也可以告诉它使用 30 分钟的间隔作为 y 轴的刻度间隔?
    • 找到了 ax.yaxis.set_major_locator(plt.MultipleLocator(1*60*30))
    猜你喜欢
    • 1970-01-01
    • 2015-06-14
    • 1970-01-01
    • 1970-01-01
    • 2012-06-16
    • 2020-01-08
    • 1970-01-01
    • 2020-10-16
    • 1970-01-01
    相关资源
    最近更新 更多