Following on from this quesiton: Set sqrt as yaxis scale from dropdown or button-Python/Plotly
I want to :
- 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)
- 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)
- 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()