I’m trying to make a dropdown with dash.plot (plotly) from an uploaded file, I already have the code to import the file as csv and excel, and I used the last example of https://dash.plot.ly/getting-started-part-2 to update the dropdown through the columns of the dataframe.
1ºI make a call to load the dropdown options
2º I visualize them, and then I pass them to the callback of the graph. But when I go to the web I don’t get any answer.
import base64
import io
import dash
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_html_components as html
import dash_table
import pandas as pd
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.config.suppress_callback_exceptions = True
app.layout = html.Div([
dcc.Upload(
id='datatable-upload',
children=html.Div([
'Drag and Drop or ',
html.A('Select Files')
]),
style={
'width': '100%', 'height': '60px', 'lineHeight': '60px',
'borderWidth': '1px', 'borderStyle': 'dashed',
'borderRadius': '5px', 'textAlign': 'center', 'margin': '10px'
},
),
dash_table.DataTable(id='datatable-upload-container'),
dcc.Dropdown(id='dropdown-values',
placeholder='Selección de variables'),
dcc.Graph(id='datatable-upload-graph')
])
def parse_contents(contents, filename):
content_type, content_string = contents.split(',')
decoded = base64.b64decode(content_string)
if 'csv' in filename:
# Suponga que el usuario ha subido un archivo CSV.
return pd.read_csv(io.StringIO(decoded.decode('utf-8')))
elif 'xls' in filename:
# Suponga que el usuario subido un fichero excel.
return pd.read_excel(io.BytesIO(decoded))
@app.callback(Output('datatable-upload-container', 'data'),
[Input('datatable-upload', 'contents')],
[State('datatable-upload', 'filename')])
def update_output(contents, filename):
if contents is None:
return [{''}]
df = parse_contents(contents, filename)
return df.to_dict('records')
@app.callback(
Output('datatable-upload-dropdown', 'options'),
[Input('datatable-upload-container', 'data')])
def set_options(options):
df = pd.DataFrame(options)
df.to_list
return [{'label': i, 'value': i} for i in df(options)]
@app.callback(
Output('dropdown-values', 'value'),
[Input('datatable-upload-dropdown', 'options')])
def set_cities_value(available_options):
return available_options[0]['value']
@app.callback(Output('datatable-upload-graph', 'figure'),
[Input('dropdown-values', 'value')])
def display_graph(rows):
df = pd.DataFrame(rows)
return {
'value': [{
'x': df[df.columns[0]],
'y': df[df.columns[1]],
'type': 'bar'
}]
}
if __name__ == '__main__':
app.run_server(debug=True,port=3005)