python - 使用 Fig.update_layout Plotly 更新 Traces 的可见性

标签 python pandas plotly

继此问题之后:Set sqrt as yaxis scale from dropdown or button-Python/Plotly

我想要:

  1. 定义包含所有迹线的绘图:visible = False
fig.add_scatter(mode="markers", x=df["gdpPercap"], y=df["lifeExp"], visible = False) #set both vis to False 
fig.add_scatter(mode="markers", x=df["gdpPercap"], y=np.sqrt(df["lifeExp"]), visible = False)
  • 创建一个更新按钮,可以使trace1或trace2变得可见
  • # buttons for updatemenu
    buttons = [dict(method='restyle',
                    label='linear',
                    visible=True,
                    args=[{'label': 'linear',
                           'visible':[True, False],
                          }
                         ]),.....
             
     um = [{'buttons':buttons,
          'direction': 'down'}
          ]
    
    fig.update_layout(updatemenus=um)
    
  • 将初始条件设置为trace1 = 可见,trace2 = 不可见
  • fig.update_layout(dict(args = {"visible": [True, False]}))
    

    前两点已经解决。 我找不到预设初始显示条件的方法。在此示例中,我可以在创建跟踪时轻松​​更改可见性,但在我的实际问题中,这会更困难。

    这是完整的示例:

    import numpy as np
    import plotly.graph_objects as go
    import plotly.express as px
    df = px.data.gapminder().query("year == 2007")
    
    # figure setup
    fig = go.Figure()
    fig.add_scatter(mode="markers", x=df["gdpPercap"], y=df["lifeExp"], visible = False) #set both vis to False 
    fig.add_scatter(mode="markers", x=df["gdpPercap"], y=np.sqrt(df["lifeExp"]), visible = False)
    
    # buttons for updatemenu
    buttons = [dict(method='restyle',
                    label='linear',
                    visible=True,
                    args=[{'label': 'linear',
                           'visible':[True, False],
                          }
                         ]),
               dict(method='restyle',
                    label='sqrt',
                    visible=True,
                    args=[{'label': 'linear',
                           'visible':[False, True],
                          }
                         ])]
               
    # specify updatemenu        
    um = [{'buttons':buttons,
          'direction': 'down'}
          ]
    
    fig.update_layout(updatemenus=um)
    
    
     #Update plot before showing to make 1st trace visible COMMENTED OUT CODE NOT WORKING 
    # fig.update_layout(dict(args = {"visible": [True, False]}))
    
    fig.show()
    

    最佳答案

    在这种情况下,您可以有条件地更新跟踪,如下所示 here .

    首先,当您添加每条迹线时,为其指定一个名称(在本例中使用“线性”和“sqrt”):

    fig.add_scatter(mode="markers", x=df["gdpPercap"], y=df["lifeExp"], 
                    visible = False, name='linear')
    fig.add_scatter(mode="markers", x=df["gdpPercap"], y=np.sqrt(df["lifeExp"]), 
                    visible = False, name='sqrt')
    

    然后稍后使用条件更新,如果名称是“线性”,则设置 visible=True:

    fig.for_each_trace(
        lambda trace: trace.update(visible=True) if trace.name == "linear" else (),
    )
    

    完整示例:

    import numpy as np
    import plotly.express as px
    import plotly.graph_objects as go
    df = px.data.gapminder().query("year == 2007")
    
    fig = go.Figure()
    # adding names for reference
    fig.add_scatter(mode="markers", x=df["gdpPercap"], y=df["lifeExp"], 
                    visible = False, name='linear')
    fig.add_scatter(mode="markers", x=df["gdpPercap"], y=np.sqrt(df["lifeExp"]), 
                    visible = False, name='sqrt')
    
    # buttons for updatemenu
    buttons = [dict(method='restyle',
                    label='linear',
                    visible=True,
                    args=[{'label': 'linear',
                           'visible':[True, False],}]),
               dict(method='restyle',
                    label='sqrt',
                    visible=True,
                    args=[{'label': 'linear',
                           'visible':[False, True],}])]
               
    # specify updatemenu        
    um = [{'buttons':buttons, 'direction': 'down'}]
    fig.update_layout(updatemenus=um)
    
    # Conditionally Updating Traces 
    fig.for_each_trace(
        lambda trace: trace.update(visible=True) if trace.name == "linear" else (),
    )
    fig.show()
    

    关于python - 使用 Fig.update_layout Plotly 更新 Traces 的可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66414456/

    相关文章:

    javascript - 我可以将 JS 脚本放在页脚上方而不是页脚下方 </body> 标记之前吗

    python - Pandas:Set_index 函数不删除列

    python - 从逐笔报价数据到 Renko 图表

    python - 如何将一行拆分为多行并在数据框列上应用日期时间?

    R:ggplot 和 plotly 轴边距不会改变

    python - 如何使用 matplotlib 生成新的彩虹色图?

    python - 如何在子标题下正确显示图像

    python - (P, Q) 和 (R,) 之间的曼哈顿距离

    R plotly : Add segment on Boxplot plotly

    python - Plotly:如何将分类变量插入平行坐标图中?