【问题标题】:Plotly Python: sort bar descending with multiple subplotsPlotly Python:使用多个子图降序排序条
【发布时间】:2022-08-23 00:48:05
【问题描述】:

我在 Python 中有一个 4 图表子图,用于帮助计算模型选择。这些模型是回归模型,所以我混合使用了直方图(预测 x 实际值)和条形图(训练、测试、CV 分数)。我的代码如下:

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\'}})

我的输出如下:

我的问题是,我如何制作底部的三个条形图,以便它们与条形图应该是一致的?我想对其中的每一个进行降序排序,但我唯一能找到的是 fig.update_layout({'xaxis':'total descending'}),它不起作用。

当涉及到多个子图时,如何按降序排序?

    标签: python plotly bar-chart


    【解决方案1】:

    想通了 - 在绘图之前重新排序数据框的简单解决方案。

    for score in scores_kf_df.T.columns:
        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=1, col=1)
    

    这里的 df_sorted 只是所有按降序排序的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-28
      • 1970-01-01
      • 2021-11-05
      • 2017-03-02
      • 2021-07-13
      • 1970-01-01
      • 1970-01-01
      • 2021-09-29
      相关资源
      最近更新 更多