I would like to create a plotly plot where I can change the value of the plotly express color
argument via a
CodePudding user response:
For color='species', three graphs are internally created for each categorical variable. And color='petal_length' consists of a single graph data. So, it is possible to handle this by setting the drop-down to show/hide the graph. The actual code reuses the data created by express.scatter. The data for each graph will be configured in a graph object; three will be shown and one will be hidden. Set the button to restyle as a function of the button.
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
df = pd.read_csv("https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv")
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(
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"
),
]),
showactive=True,
x=0.05,
xanchor="left",
y=1.2,
yanchor="top"
),
]
)
fig.update_layout(
annotations=[
dict(text="color", x=0.01, xref="paper", y=1.16, yref="paper",
align="left", showarrow=False),
])
fig.update_layout(xaxis_title_text='sepal_length', yaxis_title_text='sepal_width', legend_title_text='species')
fig.show()