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

Graph not updating using the data uploaded by user

Hi, I am trying to develop an application where the user will be given an option to provide a data set for which he wants the plot to update. And once the file is uploaded, the data points in the excel file will be plotted on the graph just like points of a scatter plot.

I am using the following code to plot the graph once the data is uploaded, however in the ‘update_figure’ function the condition ‘if contents is not None:’ is not getting satisfied. Help me resolve the issue, my code is as follows:

import dash
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_html_components as html
import dash_table_experiments as dt
import plotly.graph_objs as go

import base64
import json
import pandas as pd
import plotly
import io

app = dash.Dash()

app.scripts.config.serve_locally = True

app.layout = html.Div([
html.Div(id=‘waitfor’),
html.H1(‘Office Locator’),

dcc.Upload(
    id='upload',
    children=html.Div([
        'Drag and Drop or ',
        html.A('Select a .xlsx File')
    ]),
    style={
        'width': '100%',
        'height': '60px',
        'lineHeight': '60px',
        'borderWidth': '1px',
        'borderStyle': 'dashed',
        'borderRadius': '5px',
        'textAlign': 'center',
        'margin': '10px'
    }
),

dcc.Graph(id='examplegraph'),

html.Div(id=‘output’),

html.Div(dt.DataTable(rows=[{}]), style={‘display’: ‘none’})

])

pre_style = {
‘whiteSpace’: ‘pre-wrap’,
‘wordBreak’: ‘break-all’,
‘whiteSpace’: ‘normal’
}

@app.callback(Output(‘examplegraph’, ‘figure’),
[Input(‘upload’, ‘contents’)])

def update_figure(contents):
print(“function called”)
if contents is not None:
print(“non empty”)
content_type, content_string = contents.split(’,’)
if ‘csv’ in content_type:
df = pd.read_csv(io.StringIO(base64.b64decode(content_string).decode(‘utf-8’)))
print(“data updated csv”)
return html.Div([

dt.DataTable(rows=df.to_dict(‘records’)),

html.Hr(),

        ])
    elif 'image' in content_type:
        return html.Div([

html.Img(src=contents),

html.Hr(),

        ])
    else:
        # xlsx will have 'spreadsheet' in `content_type` but `xls` won't
        # have anything
        try:
            df = pd.read_excel(io.BytesIO(base64.b64decode(content_string)))
            print("data updated")
            go.Scatter(
                x=df['x'],
                y=df['y'],
                text=df['name'],
                mode='markers',
                opacity=0.7,
                marker={
                    'size': 15,
                    'line': {'width': 0.5, 'color': 'white'}
                },
                name=text
            )
            
            return {
                'data': df,
                'layout': go.Layout(
                    xaxis={'type': 'log', 'title': 'x'},
                    yaxis={'title': 'y'},
                    margin={'l': 40, 'b': 40, 't': 10, 'r': 10},
                    legend={'x': 0, 'y': 1},
                    hovermode='closest')
                }

        except:
            return html.Div([

html.Hr(),

            ])

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

if name == ‘main’:
app.run_server(debug=True)