kmindspark
kmindspark

Reputation: 495

Plotly express - code for plotting different columns of a histogram with a dropdown

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.

Upvotes: 1

Views: 848

Answers (1)

Derek O
Derek O

Reputation: 19565

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

Upvotes: 1

Related Questions