我正在尝试自定义图例的顺序,同时以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
中相应项目的顺序从上到下更改。
我看到Java建议here的选项。不确定如何在python中实现。
有人可以建议如何撤销订单吗?
编辑: 在生成的图像中,图例的顺序为
B
A
所需订单:
A
B
答案 0 :(得分:1)
您可以使用traceorder
键输入图例:
确定图例项目的显示顺序。如果 “正常”,则项目的显示顺序从上到下与 输入数据。如果为“反转”,则项目以相反的方式显示 顺序为“正常”。如果“分组”,则项目按组显示 (当提供跟踪
legendgroup
时)。如果是“分组+反向”,则 项目以“分组”的相反顺序显示。
对于您而言,您应该修改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'})
)
没有跟踪顺序规范
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')
具有跟踪顺序规范
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')