Sort bar descending with multiple subplots

I have a 4 chart subplot in Python that I am using to help calculate model selection. The models are regression models, so I am using a mix of histograms (predictions x actuals) and bar charts (train, test, cv scores). My code is as follows:

fig = make_subplots(3,2, specs=[[{'colspan':2}, None],
                                 [{'colspan':2}, None],
                                [{'type':'xy'}, {'type':'xy'}]
                               ],
                   subplot_titles=('Log of Predictions and Actuals','Test and Train Scores','Test Score','Cross Validation'))

fig.add_histogram(x=np.log(y_test), name='Actuals', xbins={'size':0.1},
                 row=1,col=1)
fig.add_histogram(x=np.log(preds), name='Predictions', xbins={'size':0.1},
                 row=1,col=1),

for score in ['test','train']:
    fig.add_bar(x=scores_kf_df.T.index,y=scores_kf_df.T[str(score)], name=score, row=2, col=1)
    
for score in ['test']:
    fig.add_bar(x=scores_kf_df.T.index,y=scores_kf_df.T[str(score)], name=score, row=3, col=1)

for score in ['cv']:
    fig.add_bar(x=scores_kf_df.T.index,y=scores_kf_df.T[str(score)], name=score, row=3, col=2)

fig.update_layout({'height':1200,'width':800,
                  'title':{'text':'Accuracy Metrics of Each Model','x':0.5, 'font':{'size':28}},
                  'xaxis':{'categoryorder':'total descending'}})

My output is as follows:

My question is, how do I make the bottom three bar charts so that they are in line the way bar charts should be? I would like to sort by descending for each of these, but the only thing I can find is fig.update_layout({‘xaxis’:‘total descending’}), which doesn’t work.

How do I sort by descending when it comes to multiple subplots?

I think the easiest solution would by to sort the df by the desired variables before adding each trace, or even before the loops, like:

for score in ['test','train']:
    df_sorted = scores_kf_df.T.sort_values(by=score, ascending=False)
    fig.add_bar(x=df_sorted.index,y=df_sorted[str(score)], name=score, row=2, col=1)

or:

df_sorted = scores_kf_df.T.sort_values(by='train', ascending=False)

for score in ['test','train']:
    fig.add_bar(x=df_sorted.index,y=df_sorted[str(score)], name=score, row=2, col=1)
1 Like

This worked! (scratching my head I didn’t think of this). thanks for the quick response.

1 Like