Search code examples
pythonpandasplotly

How to make secondary y-axis and subplots in plotly pandas?


I'd like to make a secondary y-axis in the 2nd plot in plotly.

The way I'm doing this is smth like:

from plotly.subplots import make_subplots
fig = make_subplots(rows=2, cols=1)  # this works
fig = make_subplots(specs=[[{'secondary_y': True}]])  # this works
fig = make_subplots(rows=2, cols=1, specs=[[{'secondary_y': True}]])  # this doesn't work

I would then generally add plots I made in pandas to the figure

fig1 = df.plot()
for k in fig1.data:
    fig.add_trace(k)

I'd like to be able for the plot in the second row to have a secondary axis, how would I go about that?


Solution

  • You need to update your code like below... More info here

    from plotly.subplots import make_subplots
    fig = make_subplots(rows=2, cols=1, specs=[[{"secondary_y": False}], [{'secondary_y': True}]])  # this NOW works
    
    # Top
    fig.add_trace(
        go.Scatter(x=[1, 2, 3], y=[2, 52, 62], name="yaxis1 data"),
        row=1, col=1, secondary_y=False,
    )
    
    # Bottom
    fig.add_trace(
        go.Scatter(x=[1, 2, 3], y=[2, 52, 62], name="yaxis2 data"),
        row=2, col=1, secondary_y=False,
    )
    
    fig.add_trace(
        go.Scatter(x=[1, 2, 3], y=[40, 50, 60], name="yaxis3 data"),
        row=2, col=1, secondary_y=True,
    )
    
    fig.show()
    

    enter image description here