Search code examples
plotlydashboardjupyterdash

plotly graph y-axis with dropdown using dash


I am stuck with creating a responsive graph:

Does somebody have an idea what I did wrong?

# Build App
app = JupyterDash(__name__)
app.layout = html.Div([
    html.H1("Index Scatterplot"),
    dcc.Graph(id='graph'),
    html.Label([
        "constituent",
        dcc.Dropdown(
            id='constituent-dropdown', clearable=False,
            value='AAPL.O', options=[
                {'label': c, 'value': c}
                for c in ['AAPL.O', 'AMZN.O', 'TSLA.O']
            ]),
])# Define callback to update graph

@app.callback(
    Output('graph', 'figure'),
    [Input("constituent-dropdown", "value")]
)

def update_figure(constituent):
    return px.scatter(
        data, x=".SPX", y=constituent, color="size",
        color_continuous_scale='plasma',
        render_mode="webgl", title="Return Distribution"
    )# Run app and display result inline in the notebook

app.run_server(mode='inline', port=XXXX)

File "C:xxxx.py", line 21 def update_figure(constituent): ^ SyntaxError: invalid syntax

This is the base-code I used, which was for changing the color.

# Build App
app = JupyterDash(__name__)
app.layout = html.Div([
    html.H1("Index Scatterplot"),
    dcc.Graph(id='graph'),
    html.Label([
        "colorscale",
        dcc.Dropdown(
            id='colorscale-dropdown', clearable=False,
            value='plasma', options=[
                {'label': c, 'value': c}
                for c in px.colors.named_colorscales()
            ])
    ]),
])# Define callback to update graph

@app.callback(
    Output('graph', 'figure'),
    [Input("colorscale-dropdown", "value")]
)

def update_figure(colorscale):
    return px.scatter(
        data, x=".SPX", y="AAPL.O", color="size",
        color_continuous_scale=colorscale,
        render_mode="webgl", title="Return Distribution"
    )# Run app and display result inline in the notebook

app.run_server(mode='inline', port=XXXX)

Any help is appreciated.


Solution

    • to make your code work I needed to source data
    • your core issue was unmatched close square and round brackets. I recommend using a code formatter to help with this
    • have included ability to define columns and colorscales in callback
    import plotly.express as px
    import dash_core_components as dcc
    import dash_html_components as html
    from dash.dependencies import Input, Output, State
    from dash.exceptions import PreventUpdate
    import dash
    from jupyter_dash import JupyterDash
    import pandas_datareader.data as web
    import datetime as dt
    
    
    data = (
        web.DataReader(
            "sp500", "fred", start="2021-01-01", end=dt.datetime.now().strftime("%d-%b-%Y")
        )
        .rename(columns={"sp500": ".SPX"})
        .join(
            web.DataReader(
                ["AAPL", "AMZN", "TSLA"], "yahoo", start="2021-01-01", end="2021-08-29"
            )["Open"].pipe(lambda d: d.rename(columns={c: f"{c}.O" for c in d.columns})),
            how="inner",
        )
    ).assign(size=lambda d: d.mean(axis=1))
    
    
    # Build App
    app = JupyterDash(__name__)
    app.layout = html.Div(
        [
            html.H1("Index Scatterplot"),
            dcc.Graph(id="graph"),
            html.Label(
                [
                    "constituent",
                    dcc.Dropdown(
                        id="constituent-dropdown",
                        clearable=False,
                        value="AAPL.O",
                        options=[
                            {"label": c, "value": c} for c in data.columns if ".O" in c
                        ],
                    ),
                ]
            ),
            html.Label(
                [
                    "colorscale",
                    dcc.Dropdown(
                        id="colorscale-dropdown",
                        clearable=False,
                        value="plasma",
                        options=[
                            {"label": c, "value": c} for c in px.colors.named_colorscales()
                        ],
                    ),
                ]
            ),
        ]
    )
    # Define callback to update graph
    
    
    @app.callback(Output("graph", "figure"), Input("constituent-dropdown", "value"), Input("colorscale-dropdown","value"))
    def update_figure(constituent, colorscale):
        return px.scatter(
            data,
            x=".SPX",
            y=constituent,
            color="size",
            color_continuous_scale=colorscale,
            render_mode="webgl",
            title="Return Distribution",
        )  # Run app and display result inline in the notebook
    
    
    app.run_server(mode="inline")