【问题标题】:Reformat matplotlib x-axis from HH:MM:SS to HH:SS将 matplotlib x 轴从 HH:MM:SS 重新格式化为 HH:SS
【发布时间】:2014-05-13 16:23:24
【问题描述】:

我每天的每一分钟都有数据点:

import numpy as np
data = np.random.random(1440,)

# I can represent minutes as integers:

mins = np.arange(1440,dtype=np.int)

# convert to datetime

import datetime
times=np.array([datetime.datetime(2014, 5, 13, int(p/60), p%60) for p in mins])

# and plot for every 20 samples:

import matplotlib.pyplot as plt
plt.plot(times[1::20], data[1::20])

给我:

如何将 x 轴格式更改为 HH:MM?

我尝试使用 datetime.time() 函数而不是 datetime.datetime() 但这会导致错误。

【问题讨论】:

    标签: python datetime numpy matplotlib


    【解决方案1】:

    您可以使用dates package 中的custom tick formatter 来根据需要呈现日期。

    扩展您的代码示例:

    import numpy as np
    import datetime
    import matplotlib.pyplot as plt
    from matplotlib import dates
    
    data = np.random.random(1440,)
    # I can represent minutes as integers:
    mins = np.arange(1440,dtype=np.int)
    # convert to datetime
    times=np.array([datetime.datetime(2014, 5, 13, int(p/60), p%60) for p in mins])
    # and plot for every 20 samples:
    plt.plot(times[1::20], data[1::20])
    
    # generate a formatter, using the fields required
    fmtr = dates.DateFormatter("%H:%M")
    # need a handle to the current axes to manipulate it
    ax = plt.gca()
    # set this formatter to the axis
    ax.xaxis.set_major_formatter(fmtr)
    
    plt.show()
    

    格式字符串根据strftime docs定义。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-06
      • 2020-12-03
      • 1970-01-01
      • 1970-01-01
      • 2017-09-27
      • 2012-09-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多