代码之家  ›  专栏  ›  技术社区  ›  iayork

熊猫在X轴刻度单位上绘制时间戳?

  •  0
  • iayork  · 技术社区  · 6 年前

    我有一个包含日期时间值的熊猫数据帧:

    日期/时间事件值
    0 2018年11月15日17:17:49 62
    1 2018年11月15日17:27:50 63
    2018年11月15日17:37:50 64
    3 2018年11月15日17:42:49 65
    4 2018年11月15日18:17:49 64
    5 2018年11月15日19:27:48 65
    6 2018年11月15日19:37:48 66
    7 2018年11月15日19:47:49 67
    8 2018年11月15日19:57:49 68
    2018年9月11日15日20:12:49 69
    
    打印(tmp.dtypes)
    
    日期/时间日期时间64[ns]
    事件值Int64
    < /代码> 
    
    

    图表如下:

    fig,ax1=plt.subflots(1,1,figsize=(8,4))。
    tmp.plot(x='日期/时间',y='事件值',legend=none,ax=ax1)
    < /代码> 
    
    

    X轴已经用适当的日期和时间格式化(并且可以使用set_major_formatter进一步格式化)。

    现在我想在图表上画一个矩形,以突出显示特定的时间。要做到这一点,我需要知道X位置。

    print([x for x in ax1.get_xticks()])
    
    【737013.72916666、737013.75、737013.770833334、737013.791666666、737013.8125、737013.83333334】
    < /代码> 
    
    
    
    
    

    fig, ax1 = plt.subplots(1,1,figsize=(8,4))
    tmp.plot(x='Date/Time',y='Event Value', legend=None, ax=ax1)
    

    enter image description here

    set_major_formatter

    print([x for x in ax1.get_xticks()])
    
    [737013.7291666666, 737013.75, 737013.7708333334, 737013.7916666666, 737013.8125, 737013.8333333334]
    

    rect = patches.Rectangle((737013.75,55),.01,100)
    ax1.add_patch(rect)
    

    enter image description here

    1 回复  |  直到 6 年前
        1
  •  1
  •   ImportanceOfBeingErnest    6 年前

    如果用 x_compat=True 选项可以确定单位是matplotlib.dates单位。否则,熊猫可能会为你决定一些单位。

    在这里,熊猫使用matplotlib日期单位。他们是 defined as :

    matplotlib表示日期,使用浮点数指定自0001-01-01 UTC以来的天数,加上1。例如,0001-01-01,06:00是1.25,而不是0.25。不支持值<1,即日期早于0001-01-01 UTC。

    但是,您不需要自己计算这些单位。matplotlib提供助手函数

    • matplotlib.dates.date2num
    • matplotlib.dates.num2date
    • matplotlib.dates.datestr2num

    你可以用它在单位之间来回计算。

    举个例子, matplotlib.dates.datestr2num("2018-11-15 19:27:48") 给你 737013.8109722222 .