Combining Multiple Subplots with Drop Down Menu Buttons

@demianeg

Your fig.data has the length equal to Ld = 2*number of companies.
Hence to avoid displaying initially all Ld traces, you must set the visibility of traces not only in the button definitions,
but also in the definition of each trace.

Thatโ€™s why I inserted the following lines of code:

Ld=len(fig.data)
for k in range(2, Ld):
    fig.update_traces(visible=False, selector = k)

that have as effect, setting visible=False, for all traces except the two corresponding to the Company A.

With your code at the selection of a Company you donโ€™t get displayed the pair Amount, Profit for that company, because your code
doesnโ€™t set visibility for all 2*Lc traces, where Lc is the number of unique companies, but only for Lc traces.

A working code is this one:

def make_multi_plot(df):
    
    fig = make_subplots(rows=2, cols=1,
                    shared_xaxes=True,
                    vertical_spacing=0.02)

    for customer in df.Company.unique():
        
        trace1 = go.Bar(
            x=df.loc[df.Company.isin([customer])].Date, 
            y=df.loc[df.Company.isin([customer])].Amount, 
            name = "Amount - " + str(customer))
        fig.append_trace(trace1,1,1)
        trace2 = go.Scatter(
                x=df.loc[df.Company.isin([customer])].Date,
                y=df.loc[df.Company.isin([customer])].Profit,
                name = "Profit - " + str(customer))
        fig.append_trace(trace2,2,1)

    Ld=len(fig.data)
    Lc =len(df.Company.unique())
    for k in range(2, Ld):
        fig.update_traces(visible=False, selector = k)
    def create_layout_button(k, customer):
        
        visibility= [False]*2*Lc
        for tr in [2*k, 2*k+1]:
            visibility[tr] =True
        return dict(label = customer,
                    method = 'restyle',
                    args = [{'visible': visibility,
                             'title': customer,
                             'showlegend': True}])    
    

    fig.update_layout(
        updatemenus=[go.layout.Updatemenu(
            active = 0,
            buttons = [create_layout_button(k, customer) for k, customer in enumerate(df.Company.unique())]
            )
        ])
    
    fig.show()
    
2 Likes