Customizing the order of legends in plotly

后端 未结 1 441
囚心锁ツ
囚心锁ツ 2020-12-06 12:47

I am trying to customize the order of legends while plotting stacked bar plots in plotly,python.

data = [
        go.Bar(
            y=df[\'sid\'],  # assig         


        
相关标签:
1条回答
  • 2020-12-06 13:46

    You can use traceorder key for legend:

    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".

    In your case, you should modify your layout definition:

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

    without traceorder specification

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

    with traceorder specification

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

    0 讨论(0)
提交回复
热议问题