0

In my Python script I gather the datetime objects for two time periods via dateutil.parser like so:

from dateutil import parser

start_date_1 = parser.parse("2010-08-01").date()
end_date_1 = parser.parse("2010-11-05").date()
start_date_2 = parser.parse("2010-11-06").date()
end_date_2 = parser.parse("2010-11-12").date()

When trying to visualize these time periods with plotly.express.timeline, there is a gap between consecutive and directly adjacent dates (2010-11-05 and 2010-11-06). Is there any way to join these two bars without overlapping the dates?

df = pd.DataFrame([
        dict(Task="period_1", Start=start_date_1, Finish=end_date_1, Stack="stack_2"),
        dict(Task="period_2", Start=start_date_2, Finish=end_date_2, Stack="stack_2"),
    ])
    
fig = px.timeline(df,
                x_start="Start",
                x_end="Finish",
                y="Stack",
                color="Task",
                hover_name="Task",
                opacity=.7,
                width=1000)

    fig.update_traces(marker_line_width=1.0, opacity=0.95)

    fig.update_layout(
        barmode="overlay",
        xaxis = dict(
            automargin=True,
            dtick="M1",
            tickformat="%Y-%m-%d",
            type="date",
            showgrid=True,
            rangeslider_visible=True),
        
        yaxis = dict(
            automargin=True,
            visible=False,
            autorange="reversed",
            showgrid=True),
        
        legend=dict(
        title=""))

enter image description here

quadratecode
  • 396
  • 1
  • 2
  • 12

1 Answers1

0

When giving a daterange to plotly, the second index will be exclusive. (i.e. You are creating a bar up to 2010-11-05 but not including it. To fix this, add 1 day to each of you endpoints.

start_date_1 = parser.parse("2010-08-01").date()
end_date_1 = parser.parse("2010-11-06").date()
start_date_2 = parser.parse("2010-11-06").date()
end_date_2 = parser.parse("2010-11-13").date()
drew wood
  • 195
  • 1
  • 5
  • Thank you for taking the time to answer. However, it seems to me that this falsifies the underlying data in order to achieve accurate visual representation which introduces a whole new set of problems into my script. If I added 1 day to the date ranges before handing them to plotly, it would also change the data displayed on hover which is hugely important for my use case. – quadratecode Dec 01 '21 at 06:47
  • You can set your X Values to the (Date + 1 day), and set the hover_info to your original dates. – drew wood Jan 27 '22 at 21:44