2

I try to make an interactive dashboard using dash from plotly. I am a beginner in it therefore I used an example to do it. The code should upload different data files from a certain folder and plot a histogram based on a certain column. The name of each file looks like "30092017ARB.csv" (date + ARB.csv). The code loops over all file names in the data-folder and print the name of files in a drop-down bottom. After selecting the name of file it should be uploaded and plot a histogram. I wrote the following code:

        import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
import pandas as pd
#
from os import listdir
from os.path import isfile, join
import numpy as np
#

mypath='/Users/Python/BeN_/data/'
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]



app = dash.Dash()

app.layout = html.Div([
    html.H2("Ausfallsreport"),
    html.Div(
        [
            dcc.Dropdown(
                id="dataFH",
                options=[{
                    'label': i,
                    'value': i
                } for i in onlyfiles],
                value=" "),
        ],
        style={'width': '25%',
               'display': 'inline-block'}),
    dcc.Graph(id='Mygraph'),
])
@app.callback(
dash.dependencies.Output('Mygraph', 'figure'),
[dash.dependencies.Input('dataFH', 'value')])
def update_graph(dataFH):
    df = pd.read_csv(mypath+dataFH, delimiter=';',encoding='cp1252') 
    # aggregate 
    dfagg = df.groupby('Bestand', as_index=False).agg({'MW': 'sum'})
    # make strings for x-axis 
    x=["BE-"+s for s in[str(s) for s in [int(x) for x in dfagg.iloc[:,0].tolist()]]]
    y=dfagg.ix[:,1].tolist()

    trace = go.Bar(x=x, y=y, name='Declined')

    return {
        'data': [trace],
        'layout':
        go.Layout(
            title='Customer Order Status for {}'.format(dataFH),
            barmode='bar',
            yaxis=dict(tickformat=".2%"))
    }


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

I get the following output under http://127.0.0.1:8050/ . The problem is that I do not get any Bar chart. Could someone help me to figure out why.

1
  • 1
    get rid of the dropdown attribute value = ' ' and replace it with placeholder = "select a file". the attribute value references a value from the dropdown which should exists among the options in the dropdown. If you do not want to make any initial selection then replace value with with the attribute placeholder which could be an instruction or a fake selection, a hint if you will and shows up greyed out in the field of the dropdown. Commented Nov 19, 2018 at 2:10

1 Answer 1

1

In case you haven't figured it out yet, the issue is that when a user initially connects, it triggers your callback. And you're setting the initial value of dropdown to

dataFH=" "

which causes

df = pd.read_csv(mypath+dataFH ... 

to throw an error because that file doesn't exist.

Different ways to fix this, but one way is to check if mypath+dataFH is a file within your callback and return an empty list for the trace if it's not a file:

def update_graph(dataFH):
    if isfile(mypath+dataFH):
        df = pd.read_csv(mypath+dataFH, delimiter=';',encoding='cp1252') 
        # aggregate 
        dfagg = df.groupby('Bestand', as_index=False).agg({'MW': 'sum'})
        # make strings for x-axis 
        x=["BE-"+s for s in[str(s) for s in [int(x) for x in dfagg.iloc[:,0].tolist()]]]
        y=dfagg.ix[:,1].tolist()

        trace = go.Bar(x=x, y=y, name='Declined')
    else: 
        trace=[]

    return {
        'data': [trace],
        'layout':
        go.Layout(
            title='Customer Order Status for {}'.format(dataFH),
            barmode='bar',
            yaxis=dict(tickformat=".2%"))
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Chris, I will try it.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.