I am trying to update a plotly graph dash with two different dropdowns as inputs.
This is my sample dataframe:
import pandas as pd
df1 = {'category' : ['A','A','A','B','B','B'],'subcategory' : ['x', 'y', 'z', 'x1','y1','z1'],
'x_coord' : [1, 2,3,2,2,2],'y_coord' : [1,3,2,1,3,2]}
df_test = pd.DataFrame(df1)
df_test
And what I pretend to do is if I select category A, that plots in a scatter all the correspondent points to the category, but If Also I select a subcategory that modifies the graph plotting only the correspondent category-subcategory point of the dataframe.
The code is below, and it works if I only add the callback of the first dropdown, but when I add the second callback to the subcategory it doesn't work.
I am following the suggestions in the dash plotly tutorial where it says:
A word of caution: it's not always a good idea to combine Outputs, even if you can:
If the Outputs depend on some but not all of the same Inputs, keeping them separate can avoid unnecessary updates.
If they have the same Inputs but do independent computations with these inputs, keeping the callbacks separate can allow them to run in parallel.
Dash documentation callbacks
But anyway if I put the output in separate callbacks or in the same I cannot make it work, here is the code that I am trying (using jupyter notebook):
import dash
import plotly as py
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.graph_objects as go
from jupyter_plotly_dash import JupyterDash
py.offline.init_notebook_mode(connected = True)
app = JupyterDash('Test')
app.layout = html.Div([
dcc.Dropdown(id='dropdown1',
options=[{'label':i, 'value':i} for i in df_test['category'].unique()]),
dcc.Dropdown(id='dropdown2',
options=[{'label':i, 'value':i} for i in df_test['subcategory'].unique()]),
dcc.Graph(id='graphic')
])
#app.callback(
Output('dropdown2', 'options'),
[Input('dropdown1', 'value')])
def update_drop2(selected_drop):
filtered_df = df_test[(df_test.category == selected_drop)]
return [{'label':i, 'value':i} for i in filtered_df['subcategory'].unique()]
#app.callback(
Output('graphic', 'figure'),
[Input('dropdown1', 'value')])
def update_figure(selected_drop):
filtered_df = df_test[(df_test.category == selected_drop)]
fig = go.Figure()
fig.add_trace(go.Scatter(x=filtered_df.x_coord,y=filtered_df.y_coord, marker = dict(size=15, color='green'), mode='markers'))
return fig
#app.callback(
Output('graphic', 'figure'),
[Input('dropdown2', 'value')])
def update_figure(selected_drop):
filtered_df = df_test[(df_test.subcategory == selected_drop)]
fig = go.Figure()
fig.add_trace(go.Scatter(x=filtered_df.x_coord,y=filtered_df.y_coord, marker = dict(size=15, color='green'), mode='markers'))
return fig
app
If I use multiple inputs on the callback like this:
#app.callback(
Output('graphic', 'figure'),
[Input('dropdown1', 'value'), Input('dropdown2', 'value')])
def update_figure(selected_drop1, selected_drop2):
if not selected_drop2:
filtered_df = df_test[(df_test.category == selected_drop1)]
else:
filtered_df = df_test[(df_test.category == selected_drop1) &
(df_test.subcategory == selected_drop2)]
fig = go.Figure()
fig.add_trace(go.Scatter(x=filtered_df.x_coord,y=filtered_df.y_coord,
marker = dict(size=15, color='green'), mode='markers'))
return fig
It works better (or more near what I pretend), but however when I switch between categories I see no data.
Thanks in advance for your help and reccomendations.
I had a similar problems the trick is to add to the second dropdown an option all. Then I wanted on the second dropdown to show only the subcategories in the given category. So I actually use 2 callbacks for dropdowns and 1 callback for the plot.
app.py
import pandas as pd
import os
import plotly.graph_objs as go
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
df = pd.DataFrame({'category' : ['A','A','A','B','B','B'],
'subcategory' : ['x', 'y', 'z', 'x1','y1','z1'],
'x_coord' : [1, 2,3,2,2,2],
'y_coord' : [1,3,2,1,3,2]})
# lists of categories
options1 = sorted(df["category"].unique().tolist())
# dictionary of category - subcategories
all_options = df.groupby("category")["subcategory"].unique()\
.apply(list).to_dict()
# we add as first subcategory for each category `all`
for k, v in all_options.items():
all_options[k].insert(0, 'all')
app = dash.Dash()
app.layout = html.Div([
dcc.Dropdown(
id='first-dropdown',
options=[{'label': k, 'value': k} for k in all_options.keys()],
value=options1[0]
),
html.Hr(),
dcc.Dropdown(id='second-dropdown'),
html.Hr(),
dcc.Graph(id='display-selected-values')
])
# the following two callbacks generate a dynamic 2 option
#app.callback(
dash.dependencies.Output('second-dropdown', 'options'),
[dash.dependencies.Input('first-dropdown', 'value')])
def set_2_options(first_option):
return [{'label': i, 'value': i} for i in all_options[first_option]]
#app.callback(
dash.dependencies.Output('second-dropdown', 'value'),
[dash.dependencies.Input('second-dropdown', 'options')])
def set_2_value(available_options):
return available_options[0]['value']
#app.callback(
dash.dependencies.Output('display-selected-values', 'figure'),
[dash.dependencies.Input('first-dropdown', 'value'),
dash.dependencies.Input('second-dropdown', 'value')])
def update_graph(selected_first, selected_second):
if selected_second == 'all':
ddf = df[df["category"]==selected_first]
else:
ddf = df[(df["category"]==selected_first) &
(df["subcategory"]==selected_second)]
fig = go.Figure()
fig.add_trace(
go.Scatter(x=ddf["x_coord"],
y=ddf["y_coord"],
marker = dict(size=15, color='green'),
mode='markers'))
return fig
if __name__ == '__main__':
app.run_server(debug=True, port=8051)
Related
I'm trying to display live location data on a mapbox scatter plot. In order to mimic new data received from the server the callback moves all points every 3 seconds:
import plotly.express as px
from dash import Dash, html, dcc
from dash.dependencies import Input, Output
px.set_mapbox_access_token(open(".mapbox_token").read())
df = px.data.carshare()
app = Dash(__name__)
app.layout = html.Div([
dcc.Graph(id='map', animate=True),
dcc.Interval(
id='interval-component',
interval=3000,
)
])
#app.callback(Output('map', 'figure'), [Input('interval-component', 'n_intervals')])
def update_map(n):
df['centroid_lon'] += 0.01
fig = px.scatter_mapbox(df, lat="centroid_lat", lon="centroid_lon")
return fig
if __name__ == '__main__':
app.run_server(debug=True)
While the labels are correctly changing their location, the markers are stuck at their original positions.
result
I found a work around by having two callbacks.
my html looks like this dbc.Col > dcc.Graph(figure = fig)
#app.callback(
Output('graph-id','figure'),
Input('control-id', 'n_clicks')
)
def update_func(scatter_map_fig):
return go.Figure
The second callback returns a new graph component with the updated information of the figure
#app.callback(
Output('col-id','children'),
Input('graph-id', 'figure'),
State('date_range','start_date'),
State('date_range','end_date'),
)
def update_func_2(scatter_map_fig):
scatter_fig = go.Figure()
scatter_fig.update_layout(...)
... (put your figure logic here)
return dcc.Graph(figure=fig)
It is a bit janky but it works until there's a better solution. Hope it helps.
I'm not clear how I could dynamically create multiple charts at once - or if that is not possible then how I could loop through a list of values using a single callback.
For example in the code below list of continents is a a list of filter options. Is it possible to basically make it so when this page loads, I see 5 charts automatically?
Currently, what I'm doing is I have to type 5 #app.callback...make_scatter_plot(option=_dropdown_value) which ends up with a million lines of code in my file and makes it hard to read even though everything is doing the same thing.
What am I missing? Thanks
from dash import Dash, dcc, html, Input, Output
import plotly.express as px
import pandas as pd
import numpy as np
app = Dash(__name__)
df = px.data.gapminder()
list_of_continents = ["Asia", "Africa", "Europe", 'Oceania', 'Americas']
app.layout = html.Div([
html.H4('Restaurant tips by day of week'),
dcc.Dropdown(
id="dropdown",
options=list_of_continents,
multi=False
),
dcc.Graph(id="graph"),
#dcc.Graph(id ='graph2') ##????
])
#app.callback(
Output("graph", "figure"),
Input("dropdown", "value")
)
def make_scatter_plot( value =[i for i in list_of_continents], df = df):
"""
"""
data = df[df['continent'].isin([value])]
fig = px.scatter(data, x="lifeExp", y="gdpPercap",
size="pop")
return fig
if __name__ == '__main__':
app.run_server(debug=True)
although plotly express can help you set up a graph with just one line of code it’s not very handy when it comes to customizing each trace. So, for that, you’ve to switch to graphs_objects.
In the following lines of code, the callback generates a Graph component for each trace and appends each graph component to a Div component. Hence you get multiple graphs using a single callback.
from dash import Dash, dcc, html, Input, Output
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
import numpy as np
app = Dash(__name__)
df = px.data.gapminder()
app.layout = html.Div([
html.H4('Restaurant tips by day of week'),
html.Div(id='graphs',children=[])
])
#app.callback(
Output("graphs", "children"),
Input("graphs", "children")
)
def make_scatter_plot(child):
"""
"""
for continent in df['continent'].unique():
df_filtered = df[df['continent'] == continent]
fig = go.Figure()
fig.add_trace(
go.Scatter(x = df_filtered['lifeExp'],
y = df_filtered['gdpPercap'],
mode = 'markers',
marker = dict(size = 10 + (df_filtered['pop'] - df_filtered['pop'].min()) * 20
/ (df_filtered['pop'].max() - df_filtered['pop'].min())) # This is just to scale the marker size value between 10 and 20.
)
)
fig.update_layout(
title_text = continent
)
child.append(dcc.Graph(figure=fig))
return child
if __name__ == '__main__':
app.run_server(debug=True)
The output of the Code:
Click here
I'm doing some GIS analysis and got a bit flustered.
I need to create a interactive plotly dash app, where you have two multi dropdown dash core components that update values on a px.scatter_mapbox map. The DataFrame has the following "Filters"/Fields I need in the dropdowns: Race/Ethnicity and City. I'm stuck at this point:
Click on the Race Drop down (Multi) (works)
City Options are appropriately filled (works)
Map won't update-- just returns what you see below.
Here is my code:
import dash.dependencies
import plotly.express as px
import pandas as pd
from jupyter_dash import JupyterDash
import dash_core_components as dcc
from dash import html
from dash.dependencies import Input, Output
import plotly.graph_objects as go
px.set_mapbox_access_token(mapbox_access_token)
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = JupyterDash(__name__, external_stylesheets=external_stylesheets)
re_indicators = df["RE"].unique()
city_indicators = df["CITY"].unique()
app.layout = html.Div([
html.Div(children=[
html.Label('Race & Ethnicity'),
dcc.Dropdown( id = "re",
options=[{'label': i, 'value': i} for i in re_indicators],
value = ["White"],
multi = True
),
html.Label('City'),
dcc.Dropdown( id = "city",
options=[],
value = [],
multi = True
),
html.Div([
dcc.Graph(
id='my_map',
figure = {})
])
])])
#app.callback(
dash.dependencies.Output('city', 'options'),
dash.dependencies.Input('re', 'value')
)
def re_picker(choose_re):
if len(choose_re) > 0:
dff = df[df.RE.isin(choose_re)]
return [{'label': i, 'value': i} for i in (dff.CITY.unique())]
#app.callback(
dash.dependencies.Output('city', 'value'),
dash.dependencies.Input('city', 'options')
)
def set_city_value(available_options):
return [x['value'] for x in available_options]
#app.callback(
dash.dependencies.Output('my_map', 'figure'),
[dash.dependencies.Input('re', 'value'),
dash.dependencies.Input('city', 'value')]
)
def update_figure(selected_re, selected_city):
if len(selected_re) == 0:
return print("nope")
else:
df_filtered = dff[(dff['CITY'] == selected_city)]
fig = px.scatter_mapbox(df_filtered,
lat="Latitude",
lon="Longitude",
zoom=1)
return fig
# Run app and display result inline in the notebook
if __name__ == '__main__':
app.run_server(host = "127.0.0.1", port = "8888", mode= "inline", debug = False)
Ouput Photo
you have not provided any data, have generated some sample data
there are a number issues with your code. All actually generate obvious exceptions
scoping, dff is note scoped across all callbacks however you are assuming it is. Fixes are to only have df as global scope
list equality makes no sense. use isin()
better practice is to use raise dash.exceptions.PreventUpdate if conditions for callback are not met
solution
import dash.dependencies
import plotly.express as px
import pandas as pd
from jupyter_dash import JupyterDash
import dash_core_components as dcc
from dash import html
from dash.dependencies import Input, Output
import plotly.graph_objects as go
# px.set_mapbox_access_token(mapbox_access_token)
external_stylesheets = ["https://codepen.io/chriddyp/pen/bWLwgP.css"]
app = JupyterDash(__name__, external_stylesheets=external_stylesheets)
re_indicators = df["RE"].unique()
city_indicators = df["CITY"].unique()
app.layout = html.Div(
[
html.Div(
children=[
html.Label("Race & Ethnicity"),
dcc.Dropdown(
id="re",
options=[{"label": i, "value": i} for i in re_indicators],
value=["White"],
multi=True,
),
html.Label("City"),
dcc.Dropdown(id="city", options=[], value=[], multi=True),
html.Div([dcc.Graph(id="my_map", figure={})]),
]
)
]
)
#app.callback(
dash.dependencies.Output("city", "options"), dash.dependencies.Input("re", "value")
)
def re_picker(choose_re):
if len(choose_re) > 0:
dff = df[df.RE.isin(choose_re)]
else:
raise dash.exceptions.PreventUpdate
return [{"label": i, "value": i} for i in (dff.CITY.unique())]
#app.callback(
dash.dependencies.Output("city", "value"),
dash.dependencies.Input("city", "options"),
)
def set_city_value(available_options):
return [x["value"] for x in available_options]
#app.callback(
dash.dependencies.Output("my_map", "figure"),
[dash.dependencies.Input("re", "value"), dash.dependencies.Input("city", "value")],
)
def update_figure(selected_re, selected_city):
if not selected_re or not selected_city or len(selected_re)==0 or len(selected_city)==0:
raise dash.exceptions.PreventUpdate
# df_filtered = dff[(dff['CITY'] == selected_city)] # this is out of scope!!!
df_filtered = df.loc[df["CITY"].isin(selected_city) & df["RE"].isin(selected_re)]
fig = px.scatter_mapbox(df_filtered, lat="Latitude", lon="Longitude", zoom=1).update_layout(mapbox={"style":"carto-positron"})
return fig
# Run app and display result inline in the notebook
if __name__ == "__main__":
app.run_server(host="127.0.0.1", port="8888", mode="inline", debug=False)
data
import io
import pandas as pd
df = pd.read_csv(io.StringIO("""RE,Longitude,Latitude,CITY
Black,-120.99774156574261,37.559165406261,Stanislaus
Pacific,-120.65111562736087,38.446389516422855,Amador
Pacific,-119.81550247702623,36.07536100517565,Kings
Black,-121.95120685287338,37.92342159137978,Contra Costa
Native,-118.26100262413676,34.197992401614535,Los Angeles
Asian,-120.7249673888429,41.58984787469562,Modoc
White,-121.95120685287338,37.92342159137978,Contra Costa
Hispanic,-123.9578138104391,41.74495737627584,Del Norte
Black,-122.39220680431815,39.59840477506362,Glenn
Pacific,-122.04052155027398,40.7637665910163,Shasta
Black,-120.71766862423333,37.19185694553567,Merced
Native,-121.69484223375345,39.03452277403378,Sutter
Black,-115.9938588669452,33.743676039870444,Riverside
Black,-119.90551726806129,37.58152187924647,Mariposa
Pacific,-117.41078970333236,36.51112681410214,Inyo
Black,-119.76264585146096,37.218035870388235,Madera
Pacific,-123.43155392039253,39.433623844726505,Mendocino
Black,-121.34428014540734,38.4493728777556,Sacramento
White,-120.7249673888429,41.58984787469562,Modoc
Pacific,-119.64932124370894,36.758179506828185,Fresno
White,-119.81550247702623,36.07536100517565,Kings
Native,-121.91788591709779,37.65054956250571,Alameda
Asian,-121.07499558470187,36.6057059207284,San Benito
Native,-120.52464692805631,38.778737966889466,El Dorado
Pacific,-120.55413218695809,38.204606401638536,Calaveras
Hispanic,-116.17845588321354,34.84143467938159,San Bernardino
Black,-122.23388486629841,40.12573617303074,Tehama
White,-121.90162044594241,38.68664649354098,Yolo
Native,-120.45219691432906,35.38741552944272,San Luis Obispo
Pacific,-119.82065303166894,38.59725063024503,Alpine"""))
i want to build a DataTable which gets updated from time to time. Each time this happens, the table is supposed to fetch the data from a csv file. In order to do this i build a function that generates and returns the table. This works, after the second update - but the first table i generated stays and therefore i end up with to tables where one does what i want but the other one just stays...:
The one on top is the second one, which updates. The one in the bottom is the on i generated first,
This is my code:
import random
import dash
from dash.dependencies import Input, Output, State
import dash_table
import dash_html_components as html
import pandas as pd
df = pd.read_csv('.../dummy2_csv.csv')
def maketable(dataf):
tab = html.Div([dash_table.DataTable(
id='adding-rows-table',
editable=True,
data=dataf.to_dict('rows'),
columns=[{'name': i, 'id': i} for i in dataf.columns])])
return tab
app = dash.Dash(__name__)
app.layout = html.Div([
html.Div(id='my-div'),
maketable(df),
html.Button('+', id='editing-rows-button', n_clicks=0),
html.Button('update', id='btn-save', n_clicks=0)
])
#app.callback(
Output(component_id='my-div', component_property='children'),
[Input('btn-save', 'n_clicks'), Input('adding-rows-table', 'data')]
)
def update_output_div(n_clicks, data):
changed_id = [p['prop_id'] for p in dash.callback_context.triggered][0]
if 'btn-save' in changed_id:
df2 = pd.DataFrame(data)
for col in df2.columns:
# new values
df2[col].values[:] = random.randint(0,9)
df2.to_csv('.../dummy2_csv.csv', encoding='utf-8', index=False)
return maketable(df2)
#app.callback(
Output('adding-rows-table', 'data'),
[Input('editing-rows-button', 'n_clicks')],
[State('adding-rows-table', 'data'),
State('adding-rows-table', 'columns')])
def add_row(n_clicks, rows, columns):
if n_clicks > 0:
rows.append({c['id']: '' for c in columns})
return rows
if __name__ == '__main__':
app.run_server(debug=True)
Thanks in advance for your help!
best, t.
I got it to work
the issue, was in callback function.
check:
import dash
from dash.dependencies import Input, Output, State
import dash_table
import dash_daq as daq
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
df = pd.read_csv('.../dummy2_csv.csv')
body = dbc.Container(
[
dbc.Row(
[
dash_table.DataTable(id="dash_neu", editable=True, row_deletable=True, columns=[{'name': i, 'id': i} for i in df.columns], data=df.to_dict('records')),
dbc.Col(html.Button('+', id='editing-rows-button', n_clicks=0)),
dbc.Col(html.Button('update', id='btn-save', n_clicks=0))
]
)])
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
app.layout = html.Div([body])
#app.callback(
[dash.dependencies.Output("dash_neu", "data"), dash.dependencies.Output("dash_neu", "columns")],
[Input("btn-save", "n_clicks"), Input('editing-rows-button', 'n_clicks')],
[State('dash_neu', 'data'), State('dash_neu', 'columns')]
)
def update(button, clicked, data, columns):
changed_id = [p['prop_id'] for p in dash.callback_context.triggered][0]
if 'btn-save' in changed_id:
df = pd.DataFrame(data)
df.to_csv('.../dummy2_csv.csv', encoding='utf-8', index=False)
columns = [{'name': i, 'id': i} for i in df.columns]
data = df.to_dict('records')
return data, columns
if 'editing-rows-button' in changed_id:
if clicked > 0:
data.append({c['id']: '' for c in columns})
return data, columns
return data, columns
It looks like the problem is because you've called the function to build the table outside of the div which receives the table from your callback. Try changing your layout to this:
app.layout = html.Div([
html.Div(id='my-div', children=[maketable(df)]),
html.Button('+', id='editing-rows-button', n_clicks=0),
html.Button('update', id='btn-save', n_clicks=0)
])
I would like to add a dropdown menu to show only one figure. I mean, if I select fig the dash must show me only the fig and if I select fig2 the dash must show me the fig 2. Is it possible?
My code is an example, I have more than 500 figs.
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objects as go # or plotly.express as px
fig = go.Figure()
fig2 = go.Figure()
fig.add_trace(go.Scatter(y=[4, 2, 1], mode="lines"))
fig2.add_trace(go.Bar(y=[2, 1, 3]))
figs = [fig, fig2]
div = []
for item in figs:
div.append(dcc.Graph(figure=item))
app = dash.Dash()
app.layout = html.Div(div)
"""
add a dropdown to show only one fig
"""
app.run_server(debug=True, use_reloader=False)
Yes, it is possible.
First you need to create the dropdown containing the figure-names / filenames or the identifier you wish, just keep the {'label': x, 'value': x} structure for the option parameter. label is what you will see in the dropdown, and value will be passed to the callback (s. below).
fig_names = ['fig1', 'fig2']
fig_dropdown = html.Div([
dcc.Dropdown(
id='fig_dropdown',
options=[{'label': x, 'value': x} for x in fig_names],
value=None
)])
Next you need a blank div (with an id) where the plot will appear:
fig_plot = html.Div(id='fig_plot')
Now create a callback. When an input with the id='fig_dropdown' is changed, the value parameter will be passed to the update_output function. The output of this function will be passed to passed to the children parameter of the id='fig_plot' div.
#app.callback(
dash.dependencies.Output('fig_plot', 'children'),
[dash.dependencies.Input('fig_dropdown', 'value')])
def update_output(fig_name):
return name_to_figure(fig_name)
The name_to_figure(fig_name) function returns a dcc.Graph() objects, containing your figure, depending on the fig_name value of the dropdown.
Full example:
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objects as go # or plotly.express as px
app = dash.Dash()
fig_names = ['fig1', 'fig2']
fig_dropdown = html.Div([
dcc.Dropdown(
id='fig_dropdown',
options=[{'label': x, 'value': x} for x in fig_names],
value=None
)])
fig_plot = html.Div(id='fig_plot')
app.layout = html.Div([fig_dropdown, fig_plot])
#app.callback(
dash.dependencies.Output('fig_plot', 'children'),
[dash.dependencies.Input('fig_dropdown', 'value')])
def update_output(fig_name):
return name_to_figure(fig_name)
def name_to_figure(fig_name):
figure = go.Figure()
if fig_name == 'fig1':
figure.add_trace(go.Scatter(y=[4, 2, 1]))
elif fig_name == 'fig2':
figure.add_trace(go.Bar(y=[2, 1, 3]))
return dcc.Graph(figure=figure)
app.run_server(debug=True, use_reloader=False)
Incase you have so many fig to choose from in your Drop Down box, the following changes to the code may be necessary to implement:
#app.callback(Output('fig_plot', 'figure'), [Input('fig_dropdown', 'value')])
def cb(plot_type):
plot_type = plot_type if plot_type else 'fig1'
df_year = head_db.copy()
if plot_type:
return px.bar(df_year, x='Week #', y=str(plot_type), color='Name')
#Libraries/Imports
from dash import Dash, html, dcc, Input, Output
import plotly.graph_objects as go
fig = go.Figure()
fig2 = go.Figure()
fig.add_trace(go.Scatter(y=[4, 2, 1], mode="lines"))
fig2.add_trace(go.Bar(y=2, 1, 3]))
figs = ['fig', 'fig2']
#Your HTML to display the graph
#Disables the multiple dropdown values attributes
app.layout = html.Div([
html.Div(children=[
html.label('Dropdown'),
dcc.Dropdown(id='dropdown', options=(figs), multi=False
html.div(id='show-my-graph')
])
])
#Your callback; is used to display the graph when the dropdown values are selected or updated
#app.callback(
Output(component_id='show-my-graph'), component_property='children'),
Input(component_id='dropdown', component_property='value')
)
#Defines the Function used to display the graph when an option is selected or updated
def update_graph(dropdown_value):
"Returns the appropriate graph component to display when a dropdown is selected or updated"
if(dropdown_value == 'fig'):
ret_val = dcc.Graph(id='scatter-plot-graph', figure=fig)
return ret_val
if (dropdown_value == 'fig2'):
ret_val = dcc.Graph(id='bar-graph', figure=fig2)
return ret_val
app.run_server(debug=True, use_reloader=False)