Black Lives Matter. Please consider donating to Black Girls Code today.

Display Data and Select from drop down to plot the graph

Hi,

I am new to dash library for python. I need help with the data display and selecting data for the plot. There are dash examples of displaying the data, however my display isn’t working. I am unable to figure out why. Please find part of my code below

import base64
import datetime
import io

import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
import dash_table_experiments as dt

import pandas as pd


app = dash.Dash()

app.scripts.config.serve_locally = True

app.layout = html.Div(children=[
    html.H1(children='Data Analytics', style ={'textAlign':'center'}),

    html.Div([
        dcc.Upload(
            id='upload-data',
            children=html.Div(['Select File']),
        style={

            'width': '90%',
            'height': '35px',
            'lineHeight': '35px',
            'borderWidth': '1px',
            'borderColor': 'lightgrey',
            'borderStyle': 'solid',
            'borderRadius': '5px',
            'textAlign': 'center',
            'textColor': 'grey',
            'margin': '10px'
        },

        multiple=False
    ),

        dcc.Dropdown(

            options=[
                {'label': 'Chlorine Intake (1996-2000)', 'value': 'show_absolute_chlorineintake'},

                {'label': 'Sulphate Intake (1999-2016)', 'value': 'absolute_sulhateintake_all_time'},

                {'label': 'Floride Intake (single year)', 'value': 'show_florideintake_single_year'}],

            value='',

            id='chart-dropdown',

            placeholder='Select Dataset'


        ),

    ],style={'columnCount': 2}),

    html.Br(),

    html.Div(id='output-data-upload'),
    html.Div(dt.DataTable(rows=[{}]), style={'display': ''}),

    html.Br(),

    dcc.Graph(
        id='example-graph',
        figure={
            'data': [
                {'x': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], 'y': [4, 1, 2, 4, 2, 5, 6, 3, 4, 6, 7, 4, 3, 2,], 'mode': 'line', 'name': 'Liquid Methane'}
            ],
            'layout': {
                'title': 'Chemical Intake'
            }
        }),


])


def parse_contents(contents, filename, date):
    content_type, content_string = contents.split(',')

    decoded = base64.b64decode(content_string)
    try:
        if 'csv' in filename:
            df = pd.read_csv(
                io.StringIO(decoded.decode('utf-8')))
        elif 'xls' in filename:
            df = pd.read_excel(io.BytesIO(decoded))
    except Exception as e:
        print(e)
        return html.Div([
            'There was an error processing this file.'
        ])

    return html.Div([
        html.H5(filename),
        html.H6(datetime.datetime.fromtimestamp(date)),

        dt.DataTable(rows=df.to_dict('records')),

        html.Hr(),

        html.Div('Raw Content'),
        html.Pre(contents[0:200] + '...', style={
            'whiteSpace': 'pre-wrap',
            'wordBreak': 'break-all'
        })
    ])


@app.callback(Output('output-data-upload', 'children'),
              [Input('upload-data', 'contents'),
               Input('upload-data', 'filename'),
               Input('upload-data', 'last_modified')])

def update_output(list_of_contents, list_of_names, list_of_dates):
    if list_of_contents is not None:
        children = [
            parse_contents(c, n, d) for c, n, d in
            zip(list_of_contents, list_of_names, list_of_dates)]
        return children


app.css.append_css({
    'external_url': 'https://codepen.io/chriddyp/pen/bWLwgP.css'
})

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

I have also attached an image of data file (containing over 12000 rows) that I am using to import and display the data. Ultimately the goal is to select a column and display that as a graph.

Many Thanks for the help in advance !!

Hi, and thanks for writing in. Would it be possible to build some simpler versions of your app and see if you’re still running into issues? For example: a simple app that takes in any csv and displays a datatable. I’m unfortunately unable to help much without more context on your project, and building simple reproducible examples is the best way to diagnose a bug.

Hi Charley,

Thanks for helping. The idea here is to utilise the upload capability of dash to import/upload the csv/xls file and create a dataframe which is should be displayed as a scrollable table. The upload functionality as below allows browsing the file and opening the datafile.

html.Div([
    dcc.Upload(
        id='upload-data',
        children=html.Div(['Select File']),
    style={

        'width': '90%',
        'height': '35px',
        'lineHeight': '35px',
        'borderWidth': '1px',
        'borderColor': 'lightgrey',
        'borderStyle': 'solid',
        'borderRadius': '5px',
        'textAlign': 'center',
        'textColor': 'grey',
        'margin': '10px'
    },

    multiple=False
),

The parser function (see the code below) splits the csv based on its delimiter ‘,’ and then decoder allows reading the data as in the form of pd.read_csv to assign it to the dataframe df. This dataframe is pandas dataframe which is converted into dictionary.

def parse_contents(contents, filename, date):
content_type, content_string = contents.split(',')

decoded = base64.b64decode(content_string)
try:
    if 'csv' in filename:
        df = pd.read_csv(
            io.StringIO(decoded.decode('utf-8')))
    elif 'xls' in filename:
        df = pd.read_excel(io.BytesIO(decoded))
except Exception as e:
    print(e)
    return html.Div([
        'There was an error processing this file.'
    ])

return html.Div([
    html.H5(filename),
    html.H6(datetime.datetime.fromtimestamp(date)),

    dt.DataTable(rows=df.to_dict('records')),

    html.Hr(),

    html.Div('Raw Content'),
    html.Pre(contents[0:200] + '...', style={
        'whiteSpace': 'pre-wrap',
        'wordBreak': 'break-all'
    })
])

The callback and update function is used to update the table information, get new filename, and date of modification.

This is the slightly modified version of upload example 1 given at https://dash.plot.ly/dash-core-components/upload. I hope I have answered your question. If not please ping me back again.

Many Thanks

@shiraz I would start out even simpler than this. With your CSV, this can be tested in two ways:

  1. Is the CSV parser working? Just try to make sure that you can turn your CSV into a pandas dataframe.

  2. Then, we can find out what’s happening with the styling of the datatable.

Thanks

Did you fix the error ?

Can you share how ?