I have a data frame and want to create a scatter plot from it. The basic code is :
import plotly.express as px
fig = px.scatter(df, x="X", y="Y", color="size")
I want to interactively change the color mapping by a dropdown menu for all columns in the data frame (beside X, Y). What I need to do is probably to set this one up correctly:
fig.update_layout(
active=0,
buttons=[
# my idea would be to use a list comprehension here
dict(
label = col,
method = 'restyle',
...?
)
for col in filter( exclude_columns, df.columns)
]
)
I found this SO question Change plotly express "color" variable with button, but some things are not clear to me.
They create a px.scatter as well as multiple graph objects:
fig1 = px.scatter(df, "sepal_length", "sepal_width", color="species")
fig2 = px.scatter(df, "sepal_length", "sepal_width", color="petal_length")
fig = go.Figure()
fig.add_trace(go.Scatter(fig1.data[0], visible=True))
fig.add_trace(go.Scatter(fig1.data[1], visible=True))
fig.add_trace(go.Scatter(fig1.data[2], visible=True))
fig.add_trace(go.Scatter(fig2.data[0], visible=False))
fig.update_layout(
updatemenus=[
dict(
# One dict for each column
buttons=list([
dict(
args=["visible", [True,True,True,False]],
label="species",
method="restyle"
),
dict(
args=["visible", [False,False,False,True]],
label="petal length",
method="restyle"
),
]),
Main question:
How can I build this dropdown menu to support an arbitrary range of columns?
Sidequestions
I might have a misconception here but as I have a medium amount of columns. Creating many px.scatter objects sounds inefficient is that really necessary as just the color mapping needs to be changed?
Likewise I don't understand the visible parameter I've seen there and in other tutorials. Why has it length 4; one for every species?