jen jojo
jen jojo

Reputation: 53

How to add button to change value of data parameter of Plotly graph in Python

These two pictures below are what I want to do, but the buttons do not work.

https://i.sstatic.net/holhR.jpg

https://i.sstatic.net/zGWm1.jpg

import plotly.express as px
df = px.data.tips()

fig = px.scatter(df, x="total_bill", y="tip", color="smoker")

## How to fix this part?
fig.update_layout(
    updatemenus=[
        dict(
            type = "buttons",
            direction = "left",
            buttons=list([
                dict(
                    args=["color", "sex"],
                    label="sex",
                    method="update"
                ),
                dict(
                    args=["color", "smoker"],
                    label="smoker",
                    method="update"
                )])),])

fig.show()
##

What should I do to fix this part, or I need to use another other library to do this work?

Upvotes: 1

Views: 1696

Answers (1)

jen jojo
jen jojo

Reputation: 53

OK, I got the answer from other place like this.

import plotly.express as px
import plotly.graph_objects as go
import plotly
df = px.data.tips()

fig = px.scatter(df, x="total_bill", y="tip", color="sex")
fig.add_trace(px.scatter(df, x="total_bill", y="tip", color="smoker").data[0])
fig.add_trace(px.scatter(df, x="total_bill", y="tip", color="smoker").data[1])


updatemenus=[dict(type = "buttons", direction = "left",
             buttons=list([
             dict(args=[{'visible': [True  , True  , False , False ]} ,],
                  label = "sex"   , method="update"),

             dict(args=[{'visible': [False , False , True  , True  ]} ,],
                  label = "smoker", method="update")
             ])),]

fig.update_layout(updatemenus = updatemenus,
                  legend_title_text='')

fig.show()

Upvotes: 1

Related Questions