pythonplotlytimelinegantt-chartplotly-express

Plotly px.Timeline y marks do not adjust when using facet_row


With a simple dataFrame that look like this

df

The following code

fig = px.timeline(df, 
              x_start="Target Date Start", 
              x_end="Target Date End", 
              y="Initiative", 
              color="Status Bin", 
              facet_row="Project Key",
              template="plotly_white") 

Generates a graph that does not adjust based on facet row. I would expect only initiatives associated with a given project key to show in the y marks, but instead all initiatives are shown: enter image description here

Note that it shows only the relevant bars but it shows all y marks as opposed to filter for relevant initiatives and also it keeps the size the same across facet_rows whereas I would expect their size to be proportional to the number of initiatives in their resp. group

EDIT: r-beginners suggested fix

enter image description here


Solution

  • If your goal is to optimize the y-axis for each individual subplot, rather than to make the y-axis values common to all subplots, then a graph object can handle this, but it will break the graph visualized in the well-organized x and y axes.

    import plotly.express as px
    import plotly.graph_objects as go
    from plotly.subplots import make_subplots
    
    row_cnt = len(df['Project Key'].unique())
    fig = make_subplots(rows=row_cnt, cols=1)
    
    for idx,k in enumerate(df['Project Key'].unique()):
        dff = df[df['Project Key'] == k]
        print(dff)
        tl = px.timeline(dff,
                          x_start="Target Date Start",
                          x_end="Target Date End",
                          y="Initiative",
                          color="Status Bin")
        for t in range(len(tl.data)):
            fig.add_trace(tl.data[t], row=idx+1, col=1)
            fig.update_traces(width=0.1)
            fig.update_traces(legendgroup=k, legendgrouptitle_text=f'Project Key:{k}', row=idx+1, col=1)
            fig.update_xaxes(type='date', range=[df['Target Date Start'].min(),df['Target Date End'].max()]) 
        
    fig.update_layout(height=1200, width=1000, template="plotly_white")
    
    fig.show()