Reputation: 43
I'm drawing a Gantt chart using timeline. I want to use add_shape
to draw dependencies, but seem to be constrained to day boundaries. The examples at https://plotly.com/python/time-series/#hiding-nonbusiness-hours hints that time deltas of <1day are possible on an axis of type='date'
, but my code doesn't work.
I'm on the verge of resorting to using an int
axis and unix timestamps, which looks like I will then have a bunch more questions about how to format that stuff as dates for the ticks.
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()
Upvotes: 1
Views: 983
Reputation: 61104
You can use a combination of pd.to_datetime()
with your dates and pd.DateOffset()
like this:
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()
Upvotes: 1