[英]Plotly: Sorting the y-axis bars of a stacked bar chart by value
I have this code example using plotly that builds a stacked bar chart:我有这个使用 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()
Which outputs the following plot:输出以下图:
Is there a way to tweak the plotly layout as to order each bar's Y-axis by value?有没有办法调整绘图布局以按值对每个条形的 Y 轴进行排序?
For example in the second bar (2018-02) Client 1 has a higher value for Y, the blue bar should be on top of the red one.例如,在第二个条形 (2018-02) 中,客户端 1 的 Y 值较高,蓝色条形应位于红色条形之上。
In Plotly the traces are always displayed in the order in which they are added to the figure and there isn't a layout option that allows to change this behavior;在 Plotly 中,轨迹总是按照它们添加到图中的顺序显示,并且没有允许更改此行为的布局选项; see, for instance, this answer .例如,请参阅此答案。 This means that for each date you would need to add the traces with the smaller values before adding the traces with the larger values.这意味着对于每个日期,您需要先添加具有较小值的跟踪,然后再添加具有较大值的跟踪。 I included an example below based on your code.我根据您的代码在下面包含了一个示例。
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.