olli
olli

Reputation: 91

How to combine plotly graph_objects with yaxis left and right?

I have two express scatter-plots which I would like to combine. One of them has the yaxis on the left, the other one on the right. To combine them I transform them to plotly graph_objects and combine them. When I do this, the right y-axis vanishes. Why is that? How can I combine fig1 and fig2 and keep the corresponding y-axis left and right?

import plotly.express as px
import plotly.graph_objects as go

fig1 = px.scatter(x=[0, 1, 2, 3, 4], y=[0, 1, 4, 9, 16])
fig1.update_traces(marker=dict(
            color='red',
            size=20,
            line=dict(
                color='MediumPurple',
                width=2
            )
        ))
fig1.update_yaxes(side="left")
go_fig1 = go.Figure(data=fig1)

fig2 = px.scatter(x=[0, 1, 2, 3, 4], y=[0, 2, 8, 18, 32])
fig2.update_traces(marker=dict(
            color='blue',
            size=20,
            line=dict(
                color='MediumPurple',
                width=2
            )
        ))
fig2.update_yaxes(side="right")
go_fig2 = go.Figure(data=fig2)

go_fig = go.Figure(data=fig1.data + fig2.data)

go_fig.show()

Upvotes: 0

Views: 161

Answers (1)

hoa tran
hoa tran

Reputation: 1679

You can use subplots to make this, please check below code:

from plotly.subplots import make_subplots

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

# Add traces
fig.add_trace(
    go.Scatter(x=[0, 1, 2, 3, 4], y=[0, 1, 4, 9, 16], name="yaxis data"),
    secondary_y=False
)

fig.add_trace(
    go.Scatter(x=[0, 1, 2, 3, 4], y=[0, 2, 8, 18, 25], name="yaxis2 data"),
    secondary_y=True
)

fig.update_traces(mode='markers',marker=dict(size=20))
fig.show()

enter image description here

You can check this doc for more detail.

If you want to use px, please use this below code:

from plotly.subplots import make_subplots

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

fig1 = px.scatter(x=[0, 1, 2, 3, 4], y=[0, 1, 4, 9, 16])
fig1.update_traces(marker=dict(
            color='red',
            size=20,
            line=dict(
                color='MediumPurple',
                width=2
            )
        ))

fig2 = px.scatter(x=[0, 1, 2, 3, 4], y=[0, 2, 8, 18, 28])
fig2.update_traces(marker=dict(
            color='blue',
            size=20,
            line=dict(
                color='MediumPurple',
                width=2
            )
        ))
fig2.update_traces(yaxis="y2")
sub_fig.add_traces(fig1.data + fig2.data)
sub_fig.show()

enter image description here

Upvotes: 2

Related Questions