简体   繁体   中英

Update visibility of Traces with fig.update_layout Plotly

Following on from this quesiton: Set sqrt as yaxis scale from dropdown or button-Python/Plotly

I want to:

  1. Define a plot with all traces: 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)
  1. Create an update button that can make trace1 or trace2 become visbile
# 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)
  1. Set inital condition to be trace1 = visible, trace2 =invisible
fig.update_layout(dict(args = {"visible": [True, False]}))

The first 2 points have been solved. I cannot find a way to preset the initial display conditions. In this example i could easily change the visibility while creating the traces, but in my real problem it would be harder.

This is the full example:

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

In this case you can conditionally update the trace as shown here .

First when you add each trace give it a name (using 'linear' and 'sqrt' in this case):

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

Then later on use a conditional update that sets visible=True if the name is "linear":

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

Full example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM