【问题标题】:How to position legends inside a plot in Plotly如何在 Plotly 的图中定位图例
【发布时间】:2020-05-24 04:33:44
【问题描述】:

我从 Plotly 页面获得了此代码。我需要使背景透明并突出显示轴。还有位于情节中的传说。

import plotly.graph_objects as go

fig = go.Figure()

fig.add_trace(go.Scatter(
    x=[1, 2, 3, 4, 5],
    y=[1, 2, 3, 4, 5],
    name="Increasing"
))

fig.add_trace(go.Scatter(
    x=[1, 2, 3, 4, 5],
    y=[5, 4, 3, 2, 1],
    name="Decreasing"
))

fig.update_layout(legend_title='<b> Trend </b>')
fig.show()

上面的代码显示了下面的输出:

我的预期输出:

如何转换第一张图片以获得第二张图片的特征?

【问题讨论】:

    标签: python python-3.x graph plotly legend


    【解决方案1】:
    import plotly.graph_objects as go
    
    fig = go.Figure()
    
    fig.add_trace(go.Scatter(
        x=[1, 2, 3, 4, 5],
        y=[1, 2, 3, 4, 5],
    ))
    
    fig.add_trace(go.Scatter(
        x=[1, 2, 3, 4, 5],
        y=[5, 4, 3, 2, 1],
    ))
    
    fig.update_layout(
        legend=dict(
            x=0,
            y=.5,
            traceorder="normal",
            font=dict(
                family="sans-serif",
                size=12,
                color="black"
            ),
        )
    )
    fig.show()
    

    在 0 到 1 之间改变 x 和 y 的值

    output

    【讨论】:

      【解决方案2】:

      要更改背景颜色需要通过plot_bgcolor='rgba(0,0,0,0)', 指定,而要将图例移动到左侧,则需要明确定义位置:

      import plotly.graph_objects as go
      
      trace0 =  go.Scatter(
          x=[1, 2, 3, 4, 5],
          y=[1, 2, 3, 4, 5],
          name="Increasing"
      )
      
      trace1 = go.Scatter(
          x=[1, 2, 3, 4, 5],
          y=[5, 4, 3, 2, 1],
          name="Decreasing"
      )
      
      data = [trace0, trace1]
      layout = go.Layout(
              plot_bgcolor='rgba(0,0,0,0)',
          legend=dict(
              x=0,
              y=0.7,
              traceorder='normal',
              font=dict(
                  size=12,),
          ),
          annotations=[
              dict(
                  x=0,
                  y=0.75,
                  xref='paper',
                  yref='paper',
                  text='Trend',
                  showarrow=False
              )
          ]
      )
      fig = go.Figure(data = data,
                      layout = layout)
      
      fig.update_xaxes(showgrid=True, gridwidth=1, gridcolor='LightGray')
      fig.update_yaxes(showgrid=True, gridwidth=1, gridcolor='LightGray')
      
      fig.show()
      

      你会得到:

      【讨论】:

      • 你知道任何选项/简单的方法可以像 Matplotlib 一样自动将图例定位在图中(取决于轨迹)吗?
      猜你喜欢
      • 2019-11-14
      • 2020-07-27
      • 2021-11-23
      • 2021-12-09
      • 2019-11-05
      • 2021-01-29
      • 2019-11-04
      • 1970-01-01
      • 2019-07-08
      相关资源
      最近更新 更多