Plotly:按值对堆积条形图的 y 轴条进行排序

Plotly: Sorting the y-axis bars of a stacked bar chart by value

我有这个使用 plotly 构建堆积条形图的代码示例:

import plotly.graph_objects as go

x = ['2018-01', '2018-02', '2018-03']

fig = go.Figure(go.Bar(x=x, y=[10, 15, 3], name='Client 1'))
fig.add_trace(go.Bar(x=x, y=[12, 7, 14], name='Client 2'))

fig.update_layout(
    barmode='stack',
    yaxis={'title': 'amount'},
    xaxis={
        'type': 'category',
        'title': 'month',
    },
)
fig.show()

输出如下图:

有没有办法调整 plotly 布局以按值对每个条形的 Y 轴进行排序?
例如,在第二个条形图 (2018-02) 中,客户 1 的 Y 值较高,蓝色条形图应位于红色条形图上方。

在 Plotly 中,轨迹始终按照添加到图中的顺序显示,并且没有允许更改此行为的布局选项;例如,请参阅此 。这意味着对于每个日期,您需要在添加具有较大值的轨迹之前添加具有较小值的轨迹。我在下面根据您的代码提供了一个示例。

import plotly.graph_objects as go
import pandas as pd
import numpy as np

# data
df = pd.DataFrame({'Date': ['2018-01', '2018-02', '2018-03'],
                   'Client 1': [10, 15, 3],
                   'Client 2': [12, 7, 14],
                   'Client 3': [18, 2, 7]})

# colors
colors = {'Client 1': 'red',
          'Client 2': 'blue',
          'Client 3': 'green'}

# traces
data = []

# loop across the different rows
for i in range(df.shape[0]):

    # for each row, order the columns based on
    # their values from smallest to largest
    ordered_columns = df.columns[1:][np.argsort(df.iloc[i, 1:].values)]

    # add a separate trace for each column,
    # ordered from smallest to largest
    for column in ordered_columns:

        data.append(go.Bar(x=[df['Date'][i]],
                           y=[df[column][i]],
                           marker=dict(color=colors[column]),
                           name=column,
                           legendgroup=column,
                           showlegend=i == 0)) # show the legend only once for each column

# layout
layout = dict(barmode='stack',
              yaxis={'title': 'amount'},
              xaxis={'type': 'category', 'title': 'month'})

# figure
fig = go.Figure(data=data, layout=layout)

fig.show()