I'm developing a dash app with graphs, sliders, dropdowns, and tables. I feel it is an easy yet efficient framework + library to design interactive web apps (dashboards).
I came across a use case where I need to update the DataFrame based on the input from the dropdown. After digging the internet for a couple of days somehow I managed to do that (in an appropriate way).
I believe that there will be a simple way to achieve my requirement than the one I'm following right now.
This is the sample code that reflects my approach
import pandas as pd
import numpy as np
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
df1 = pd.read_csv('dataset1.csv')
df2 = pd.read_csv('dataset2.csv')
final_df=[df1,df2]
app = dash.Dash(__name__)
app.layout = html.Div(id='container',children=[
dcc.Dropdown(
id='user',
options=[{'label': 'User 1','value': 'u1'},
{'label': 'User 2','value': 'u2'},
{'label': 'User 3','value': 'u3'}],
value='u1',
),
dcc.Graph(id='graph'),
])
@app.callback(
Output('graph', 'figure'),
[Input('user', 'value')])
def update_graph_1(user_value) :
if user_value == 'u1':
df = final_df[0]
fig = (px.line(df, x='col1',y='col2').update_traces(mode='lines+markers'))
return fig
elif user_value == 'u2' :
df = final_df[1]
fig = (px.line(df, x='col1',y='col2').update_traces(mode='lines+markers'))
return fig
elif user_value == 'u3' :
df = final_df[3]
fig = (px.line(df, x='col1',y='col2').update_traces(mode='lines+markers'))
return fig
if __name__ == '__main__':
app.run_server()
By following the above approach I can able to get the desired result for now. But, I believe this is not the proper way to sort my requirement.
Expected Output: Once the page is loaded, when I go ahead and select the user from the dropdown menu then the respected dataframe should load into the "df". For example, if I select 'User 1' then "df" should update with the DataSet-1. Respectively if I select 'User 2 then "df" should update with the DataSet-1 and the data points in "graph" should update according to the dataset loaded into "df".
I hope my question is clear and any help here would be greatly appreciated.
Thanks