edgj4718
edgj4718

Reputation: 47

Plotly: Is it possible to add a second y axis to plotly timeline?

I am trying to add a second y axis to a plotly figure. I could not find any hint in the documentation. Is that possible?

  fig = px.timeline(df, x_start="start", x_end="end", y="duration")

fig.update_yaxes(autorange="reversed", type='category')

fig.write_html('fig.html', auto_open=True)

enter image description here

In the right part of the figure I would like to have another y axis showing information as a string.

I would be very thankful if someone can help me.

Upvotes: 1

Views: 1349

Answers (2)

smoquet
smoquet

Reputation: 371

My timeline had multiple elements in its data attribute. In my case I had to loop through fx1.data to add each trace tot fig as such:

for trace in fx1.data:
    fig.add_trace(trace, secondary_y=False)

Upvotes: 0

vestland
vestland

Reputation: 61234

Yes, it's possible to add a secondary y axis to a plotly timeline. But not directly using px.timeline. You won't be able to skip the 'standard' approach for a secondary axis using:

fig = make_subplots(specs=[[{"secondary_y": True}]])

But once you've done that, you can build several px.timeline objects using:

fx1 = px.timeline(df1, x_start="Start", x_end="Finish", y="Task")

And then "steal" components from there, such as:

fx1.data[0]

fig.layout.xaxis = fx1.layout.xaxis

And then include them in your first fig object with:

fig.add_trace(
    fx2.data[0],
    secondary_y=True,
)

Here's an example:

enter image description here

And here's the complete code:

import plotly.graph_objects as go
from plotly.subplots import make_subplots

df1 = pd.DataFrame([
    dict(Task="Job A", Start='2009-01-01', Finish='2009-02-28', Completion_pct=50),
    dict(Task="Job B", Start='2009-03-05', Finish='2009-04-15', Completion_pct=25),
#     dict(Task="Job C", Start='2009-02-20', Finish='2009-05-30', Completion_pct=75),
    dict(Task="Job C", Start='2009-04-02', Finish='2009-05-11', Completion_pct=75)
])

df2 = pd.DataFrame([
    dict(Task="Job D", Start='2009-01-01', Finish='2009-02-12', Completion_pct=50),
    dict(Task="Job E", Start='2009-03-05', Finish='2009-04-01', Completion_pct=25),
    dict(Task="Job F", Start='2009-02-20', Finish='2009-08-01', Completion_pct=75)
])


# Create figure with secondary y-axis
fx1 = px.timeline(df1, x_start="Start", x_end="Finish", y="Task")
fx2 = px.timeline(df2, x_start="Start", x_end="Finish", y="Task")

# fx1 = px.timeline(df1, x_start="Start", x_end="Finish", y="Task", color="Task")
# fx2 = px.timeline(df2, x_start="Start", x_end="Finish", y="Task", color="Task")

fig = make_subplots(specs=[[{"secondary_y": True}]])
# Add traces
fig.add_trace(
    fx1.data[0],
    secondary_y=False,
)

fig.add_trace(
    fx2.data[0],
    secondary_y=True,
)

fig.layout.xaxis = fx1.layout.xaxis

# fx1.show()
# fx2.show()
fig.data[0].opacity = 0.2
fig.data[1].width = 0.5
fig.show()

Upvotes: 3

Related Questions