Can Subplot support multiple y-axes?

@idk
I found the notebook that avoids using low plotly code when we are working with multiple yaxes. The idea is to define the fig via make_subplots, and if f"yaxis{k}" is the principal yaxis of a subplot cell, then the index for secondary yaxis associated to the same cell must be k+1, i.e. the f"yaxis{k+1}. Your choice of y2, y3 as left yaxes and y4 as right yaxis associated to the cell from row=2 did not follow this rule. That’s why you couldn’t get the right figure, passing the row=2, col=1.
This is the corresponding code adapted to the previous data:

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

fig = make_subplots(rows=2, cols=1, specs=[[{"type":"xy"}], [{"secondary_y":True}]],
                    vertical_spacing=0.05, shared_xaxes=True)

xdata=np.linspace(1, 7, 12)
trcolor= ["#636efa", "#EF553B", "#00cc96", "#ab63fa"]
fig.add_trace(go.Scatter(x=xdata, y=2+np.random.rand(12),
                         name='y1 data'), row=1, col=1)

fig.add_trace(go.Scatter(
                  x=xdata, y=-2+3*np.random.rand(12),
                  name='y2 data'), row=2, col=1)
fig.add_trace(go.Scatter(
                  x=xdata, y=1.5*np.random.rand(12),
                  name='y3 data'), row=2, col=1, secondary_y=True)
fig.add_scatter(
        x=np.linspace(1, 7, 12), y=1+2.3*np.random.rand(12),  
        name='y4 data',
        yaxis='y4',
        xaxis='x2'
         )

fig.update_layout(title_text="Subplots with multiple yaxes", title_x=0.5,
                  margin_l=2, width=750, height=450,
                  xaxis_domain= [0.3, 1], xaxis2_title='common xaxis_title',
                  xaxis2_domain=[0.3, 1],
                  
                  yaxis4=dict(anchor= 'free',
                              overlaying= 'y2',
                              side ='left',
                              position=0.17,
                              title_text='yaxis4 title',
                              titlefont_color=trcolor[3],      
                              tickfont_color=trcolor[3])
                  );


axes =["yaxis", "yaxis2", "yaxis3"]
for j, ax in enumerate(axes):
    fig.layout[ax].update(title_text=f'yaxis{j+1} title', #merge the initial dict fig.layout[ax] with a new ax related dict dict
                          titlefont_color=trcolor[j],      
                          tickfont_color=trcolor[j])
fig.show()

1 Like