【问题标题】:How to hide legend selectively in a plotly line plot?如何在情节线图中有选择地隐藏图例?
【发布时间】:2021-11-25 05:54:03
【问题描述】:

我正在努力隐藏线图中某些但不是所有线的图例。这是情节现在的样子。

Plot:

基本上我想隐藏浅灰色线条的图例,同时将彩色线条保留在原位。

这是我的代码:

import plotly.graph_objects as go

fig = go.Figure()
fig.update_layout(autosize=False, width=800, height=500, template='none')
fig.update_layout(title = 'Title', xaxis_title = 'Games', yaxis_title = 'Profit')

for team in rest_teams:
    fig.add_traces(go.Scatter(x=df['x'], y = df[team], name = team, line = {'color': '#F5F5F5'}))

for team in big_eight:
    line_dict = {'color': cmap[team]}
    fig.add_traces(go.Scatter(x=df['x'], y = df[team], name = team, line = line_dict))

fig.show()

我可以更新布局

fig.update_layout(showlegend=False)

它隐藏了整个事情并且不是最佳的。帮助将不胜感激。

【问题讨论】:

    标签: python graph plotly visualization linegraph


    【解决方案1】:

    如果我正确理解了您想要的输出,您可以将showlegend = False 用于您使用color = #F5F5F5 设置为灰色的轨迹:

    for c in cols1:
        fig.add_trace(go.Scatter(x = df.index, y = df[c], line_color = '#F5F5F5',
                      showlegend = False))
    

    然后将其留给您想要分配颜色的行,并确保将name = c 包含在:

    for c in cols2:
        fig.add_trace(go.Scatter(x = df.index, y = df[c], 
                      name = c))
    

    剧情:

    完整代码:

    import plotly.graph_objects as go
    import plotly.express as px
    import pandas as pd
    
    
    df = px.data.stocks()
    df = df.set_index('date')
    
    fig = go.Figure()
    
    cols1 = df.columns[:2]
    cols2 = df.columns[2:]
    
    for c in cols1:
        fig.add_trace(go.Scatter(x = df.index, y = df[c], line_color = '#F5F5F5',
                      showlegend = False))
    
    for c in cols2:
        fig.add_trace(go.Scatter(x = df.index, y = df[c], 
                      name = c))
    fig.update_layout(template=template
    fig.show()
    

    【讨论】:

      猜你喜欢
      • 2010-11-23
      • 2022-01-16
      • 2021-11-03
      • 2020-12-02
      • 1970-01-01
      • 1970-01-01
      • 2022-07-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多