Updating a Dash Callback Using Radioitems

Updating a Dash Callback Using Radioitems

I am fairly new to python coding so I apologize in advance for my ignorance. I am trying to create a Dash App that drops outliers using standard deviation. The user selects a standard deviation using RadioItem inputs.

My question is what amendments do I need to make to my code so that the RadioItem value updates max_deviations using a callback?

Import packages, clean the data and define a query

import dash
import plotly.express as px
from dash import Dash, dcc, html, Input, Output, State
import pandas as pd
import numpy as np

app = dash.Dash(__name__)
server = app.server

df=pd.read_csv(r'C:\SVS_GIS\POWER BI\CSV_DATA\QSAS2021.csv', encoding='unicode_escape')

#SET DATE OF VALUATION
df['TIME'] = ((pd.to_datetime(df['Sale Date'], dayfirst=True)
             .rsub(pd.to_datetime('01/10/2021', dayfirst=True))
             .dt.days
          )*-1)

df=df[df['TIME'] >= -365]

df = df.query("(SMA >=1 and SMA <= 3) and (LGA==60)")

prepare dataframe for dropping outliers

data = pd.DataFrame(data=df)
x = df.TIME
y = df.CHANGE
mean = np.mean(y)
standard_deviation = np.std(y)
distance_from_mean = abs(y - mean)

app layout

app.layout = html.Div([

html.Label("Standard Deviation Picker:", style={'fontSize':25, 'textAlign':'center'}),
    html.Br(),
       html.Label("1.0 = 68%, 2.0 = 95%, 3.0 = 99.7%", style={'fontSize':15, 
'textAlign':'center'}),
    
html.Div(id="radio_items"),
 dcc.RadioItems(      
options=[{'label': i, 'value': i} for i in [1.0, 2.0, 3.0]],
value=2.0
),          

html.Div([
    dcc.Graph(id="the_graph")]
)])

callback

@app.callback(
    Output("the_graph", "figure"),
    Input("radio_items", 'value')
)
def update_graph(max_deviations):
    not_outlier = distance_from_mean < max_deviations * standard_deviation
    no_outliers = y[not_outlier]
    trim_outliers = pd.DataFrame(data=no_outliers)
    dff = pd.merge(trim_outliers, df, left_index=True, right_index=True)
    return (dff)


    fig = px.scatter(dff, x='TIME', y='CHANGE_y',
                     
                     color ='SMA',
                     trendline='ols',
                     size='PV',
                     height=500,
                     width=800,
                     hover_name='SMA',

                     )
    return dcc.Graph(id='the_graph', figure=fig)


    

if __name__ == '__main__':
    app.run_server(debug=False)
4

1 Answer

Your dcc.RadioItems doesn't have an id prop. Add that, and make sure it matches the ID given in the callback, and you should be good.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Sophia Al-Mansoor
Author

Sophia Al-Mansoor

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.