1

Currently, I am plotting data as a histogram using the following code.

import plotly.express as px
fig = px.histogram(df, x="col_1")
fig.show()

Is there a way to have a dropdown to control which column of the dataframe is plotted in the histogram? Or is there no way to do this with plotly express?

In either case, what code do I need to achieve this functionality? Thanks.

1 Answer 1

1

I am not sure if this is possible in plotly express. You can add the traces one at a time, then pass a list of buttons to the updatemenus argument of the update_layout function, which control the visible parameter for each trace.

Here is an example using some of the columns of plotly's finance dataset:

import plotly.graph_objects as go

import pandas as pd

# Load dataset
df = pd.read_csv(
    "https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv")
df.columns = [col.replace("AAPL.", "") for col in df.columns]
df = df.set_index("Date")
df = df[["Open","High","Low","Close","Volume"]]

# Initialize figure
fig = go.Figure()

buttons = []
for col_name in df.columns:
    ## add traces
    if col_name == "Open":
        fig.add_trace(go.Scatter(
            x=df.index,
            y=df[col_name],
            name=col_name,
            visible=True
            )
        )
    else:
        fig.add_trace(go.Scatter(
            x=df.index,
            y=df[col_name],
            name=col_name,
            visible=False
            )
        )

    ## construct buttons
    buttons.append(dict(
        label=col_name,
        method="update",
        args=[{"visible": [col_name==col for col in df.columns]},
        {"title": "Yahoo"}]))

buttons_list = list(buttons)

fig.update_layout(
    updatemenus=[
        dict(buttons=buttons_list)
    ])

fig.show()

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.