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

Processing and plotting based on uploaded data

Hello,

I am new to Dash and this great community and I am working on my first Dash App.

My goal is analyzing and plotting uploaded data. For example ‘mpg.csv’ data.
data source: https://gist.github.com/omarish/5687264

Problem I have in dash is how to create call back to generate scatterplot based on input uploaded data directly? I have tried to create several versions of callback to build the connection between uploaded data and scatterplot, but none of them works.

Below is my ‘working’ code without callback connection:

Any kind of help would be highly appreciated.

Ning


import dash_core_components as dcc

import dash

import dash_html_components as html

import plotly

import dash_table_experiments as dte

from dash.dependencies import Input, Output, State

import pandas as pd

import numpy as np

import json

import datetime

import operator

import os

import base64

import io

import itertools

from io import BytesIO

from matplotlib import cm, colors, colorbar

import matplotlib.pyplot as plt

from matplotlib.patches import Rectangle

import plotly.plotly as py

import plotly.figure_factory as ff

import plotly.graph_objs as go

mpg = pd.read_csv(‘C:/Users/nwu/repositories/Dash/Dashboards/mpg.csv’)

data processing

def extract_make(df):

df['make'] = df['name'].apply(lambda x: x.split()[0])

df['make'] = df['make'].str.upper()

return df

data = extract_make(mpg)

av_mpg = data.groupby(‘make’).mpg.mean().rename(‘av_mpg’).reset_index()

df = pd.merge(data, av_mpg, how=‘outer’, left_on=[‘make’], right_on = [‘make’])

def av_mpg(df):

    if df['av_mpg'] < 20.0:

        return 1

    elif (df['av_mpg'] > 20.0) & (df['av_mpg'] < 30.0):

        return 2

    else:

        return 3

df[‘type’] = df.apply(av_mpg, axis = 1)

scatterplot

trace1 = go.Scatter(x=df[‘mpg’], y=df[‘horsepower’][df[‘type’] == 1], # Data

                mode='markers', name='type1' # Additional options

               )

trace2 = go.Scatter(x=df[‘mpg’], y=df[‘horsepower’][df[‘type’] == 2], mode=‘markers’, name=‘type2’ )

trace3 = go.Scatter(x=df[‘mpg’], y=df[‘horsepower’][df[‘type’] == 3], mode=‘markers’, name=‘type3’)

layout = go.Layout(title=‘Simple Plot from csv data’,

               plot_bgcolor='rgb(230, 230,230)')

fig = go.Figure(data=[trace1, trace2, trace3], layout=layout)

dashboard

app = dash.Dash()

app.layout = html.Div([

html.H5(“Upload Files”),

dcc.Upload(

    id='upload-data',

    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'

    },

    multiple=False),



html.Br(),

html.H5("Table"),

html.Div(dte.DataTable(rows=[{}], id='table')),

dcc.Graph(id='scatterplot',

      figure = fig)

])

file upload function

def parse_contents(contents, filename):

content_type, content_string = contents.split(',')



decoded = base64.b64decode(content_string)

try:

    if 'csv' in filename:

        # Assume that the user uploaded a CSV file

        df = pd.read_csv(

            io.StringIO(decoded.decode('utf-8')))

    elif 'xls' in filename:

        # Assume that the user uploaded an excel file

        df = pd.read_excel(io.BytesIO(decoded))



except Exception as e:

    print(e)

    return None



return df

callback table creation

@app.callback(Output(‘table’, ‘rows’),

          [Input('upload-data', 'contents'),

           Input('upload-data', 'filename')])

def update_output(contents, filename):

if contents is not None:

    df = parse_contents(contents, filename)

    if df is not None:

        return df.to_dict('records')

    else:

        return [{}]

else:

    return [{}]

callback scatterplot creation - to be created

app.css.append_css({

"external_url": "https://codepen.io/chriddyp/pen/bWLwgP.css"

})

if name == ‘main’:

app.run_server(debug=True)