plotly express timeline:比 1 天粒度更细的问题

plotly express timeline: trouble getting finer than 1 day granularity

我正在使用时间轴绘制甘特图。我想使用 add_shape 来绘制依赖关系,但似乎被限制在日期范围内。 https://plotly.com/python/time-series/#hiding-nonbusiness-hours 中的示例暗示在 type='date' 的轴上可能有 <1 天的时间增量,但我的代码不起作用。

我即将求助于使用 int 轴和 unix 时间戳,这看起来我会有更多关于如何将这些东西格式化为刻度日期的问题。

import datetime

import plotly.express as PX
import pandas

if __name__ == "__main__":
    schedule=[
        (datetime.date(2022,1,10),datetime.date(2022,1,20), 'Task1A'),
        (datetime.date(2022,1,10),datetime.date(2022,1,20), 'Task2A'),
        (datetime.date(2022,1,20),datetime.date(2022,1,30), 'Task1B'),
        (datetime.date(2022,1,20),datetime.date(2022,1,30), 'Task2B')
    ]

    df=pandas.DataFrame(
        [dict(Task=x[2], Start=x[0], Finish=x[1]) for x in schedule],
        index=[x[2] for x in schedule])

    fig = PX.timeline(df, x_start="Start", x_end="Finish", y="Task")
    fig.update_yaxes(autorange="reversed")

    for i in [0,1]:
        task=schedule[i][2]
        to_task=schedule[i+2][2]

        offset= datetime.timedelta(hours=12*i) # an attempt to move coords by less than a whole day

        fig.add_shape( type='line',
                        x0=df.at[task, "Finish"] + offset, y0=task,
                        x1=df.at[task, "Finish"] + offset, y1=to_task,
                        line=dict(color='red', width=1))

    fig.show()

Output

Desired output

您可以将 pd.to_datetime() 与日期和 pd.DateOffset() 组合使用,如下所示:

fig.add_shape(type="line",
    x0=pd.to_datetime('2009-03-05') + pd.DateOffset(hours=42),
    y0=0, x1=pd.to_datetime('2009-03-05') + pd.DateOffset(hours=42), y1=2,
    line=dict(color="red",width=3)
)

情节

完整代码:

import plotly.express as px
import pandas as pd

df = pd.DataFrame([
    dict(Task="Job A", Start='2009-01-01', Finish='2009-02-28'),
    dict(Task="Job B", Start='2009-03-05', Finish='2009-04-15'),
])

fig = px.timeline(df, x_start="Start", x_end="Finish", y="Task")
fig.update_yaxes(autorange="reversed") # otherwise tasks are listed from the bottom up

fig.add_shape(type="line",
    x0=pd.to_datetime('2009-03-05'),
    y0=0, x1=pd.to_datetime('2009-03-05'), y1=2,
    line=dict(color="RoyalBlue",width=3)
)

fig.add_shape(type="line",
    x0=pd.to_datetime('2009-03-05') + pd.DateOffset(hours=42),
    y0=0, x1=pd.to_datetime('2009-03-05') + pd.DateOffset(hours=42), y1=2,
    line=dict(color="red",width=3)
)

f = fig.full_figure_for_development(warn=False)
fig.show()