gpt4 book ai didi

python - 在 plotly 中自定义图例的顺序

转载 作者:行者123 更新时间:2023-11-28 17:58:50 28 4
gpt4 key购买 nike

我正在尝试在 plotly,python 中绘制堆叠条形图时自定义图例的顺序。

data = [
go.Bar(
y=df['sid'], # assign x as the dataframe column 'x'
x=df['A'],
orientation='h',
name='A'
),
go.Bar(
y=df['sid'],
x=df['B'],
orientation='h',
name='B'
),

]

layout = go.Layout(
barmode='stack',
title=f'{measurement}',
xaxis=dict(
title='Count',
dtick=0),
yaxis=dict(
tickfont=dict(
size=10,
),
dtick=1)
)

fig = go.Figure(data=data, layout=layout)
plot(fig, filename='plot.html')

图例的顺序以相反的顺序出现(即从下到上)。我想改变data中相应项目从上到下的顺序。

我看到了建议的选项 here对于 Java。不确定如何在 python 中实现。

有人可以建议如何颠倒顺序吗?

编辑:在生成的图像中,图例的顺序是

B
A

所需顺序:

A
B

最佳答案

您可以使用 traceorder图例键:

Determines the order at which the legend items are displayed. If "normal", the items are displayed top-to-bottom in the same order as the input data. If "reversed", the items are displayed in the opposite order as "normal". If "grouped", the items are displayed in groups (when a trace legendgroup is provided). if "grouped+reversed", the items are displayed in the opposite order as "grouped".

在你的情况下,你应该修改你的 layout 定义:

layout = go.Layout(
barmode='stack',
title=f'{measurement}',
xaxis=dict(
title='Count',
dtick=0),
yaxis=dict(
tickfont=dict(
size=10,
),
dtick=1),
legend={'traceorder':'normal'})
)

没有traceorder规范

import plotly.graph_objs as go
from plotly.offline import init_notebook_mode, iplot
init_notebook_mode(connected=True)

trace1 = go.Bar(x=['A', 'B', 'C'],
y=[20, 14, 23],
name='first')
trace2 = go.Bar(x=['A', 'B', 'C'],
y=[12, 18, 29],
name='second')

data = [trace1, trace2]
layout = go.Layout(barmode='stack',)

fig = go.Figure(data=data, layout=layout)
iplot(fig, filename='stacked-bar')

enter image description here

具有跟踪顺序规范

import plotly.graph_objs as go
from plotly.offline import init_notebook_mode, iplot
init_notebook_mode(connected=True)

trace1 = go.Bar(x=['A', 'B', 'C'],
y=[20, 14, 23],
name='first')
trace2 = go.Bar(x=['A', 'B', 'C'],
y=[12, 18, 29],
name='second')

data = [trace1, trace2]
layout = go.Layout(barmode='stack',
legend={'traceorder':'normal'})

fig = go.Figure(data=data, layout=layout)
iplot(fig, filename='stacked-bar')

enter image description here

关于python - 在 plotly 中自定义图例的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56808693/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com