Plot based on user selected option with uploaded CSV file

Hi All,

I am new this Dash writing small application where user uploads CSV file and it should populate CSV file o/p in Table format (DataTable) and then it should give an option to user to select column names (dcc.Dropdown) from the dataTable and plot scalar graph.

I am able to upload CSV file and able to select column names from drop down boxes. But after this not able to plot graph based on user selected columns/ attributes.

Can you please help us or point to any working examples of this.

Thanks…

sounds like you need to trigger the graph with a callback from the dcc.dropdown. in order to help can you tell me how are you storing th data in the csv file and how do you have your dcc graph??

for a basic construction of a callback you can see official documentation here
https://dash.plotly.com/basic-callbacks

Thanks for the reply. Yes, we are using dcc graph. Here is the code for the same


import base64
import datetime
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 plotly.graph_objs as go

import pandas as pd

external_stylesheets = [‘https://codepen.io/chriddyp/pen/bWLwgP.css’]
colors = {
“graphBackground”: “#F5F5F5”,
“background”: “#ffffff”,
“text”: “#000000
}

app = dash.Dash(name, external_stylesheets=external_stylesheets)

app.layout = html.Div([
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’
},
# Allow multiple files to be uploaded
multiple=True
),
html.Div([‘OM Names’,
dcc.Dropdown(
id=‘OM_NAME’,
options=[{‘label’: ‘’, ‘value’: ‘’}],
# value=‘upTime’,
multi=True
)
], style={‘width’: ‘50%’, ‘display’: ‘inline-block’, ‘color’: ‘blue’, ‘fontFamily’: ‘Univia Pro’,
‘fontSize’: 20}
),
html.Div([
html.Button(
id=‘SUBMIT’,
n_clicks=0,
children=‘Submit’,
style={‘fontSize’: 15, ‘marginLeft’: ‘20px’}
)
]),
html.Div(id=‘output-data-upload’),
dcc.Graph(id=‘Graph’),
html.Div(['KPI Table Info: ',
dash_table.DataTable(
id=‘KPI_Table’,
columns=[{‘name’: ‘KPI Name’, “id”: ‘KPI_Name’},{‘name’: “value”, “id”: “value”}],
#fixed_columns=1
)

])

])

def parse_data(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')))
        df.insert(0, 'DateTime', df['date'] + ' ' + df['time'])
        df.sort_values("ver", inplace=True)
        df.drop_duplicates(keep=False,inplace=True)
        #df.drop('ver', inplace=True)
    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 html.Div([
        'There was an error processing this file.'
    ])
#df['DateTime'] = pd.to_datetime(df['DateTime'], errors='ignore')

return df

This is for table representations

@app.callback(Output(‘output-data-upload’, ‘children’),
[
Input(‘upload-data’, ‘contents’),
Input(‘upload-data’, ‘filename’)
])
def update_table(contents, filename):
#table = html.Div()
if contents is not None:
contents = contents[0]
filename = filename[0]
df = parse_data(contents, filename)
columns = df.columns.values.tolist()
table = html.Div([
html.H5(filename),
dash_table.DataTable(
data=df.to_dict(‘rows’),
columns=[{‘name’: i, ‘id’: i} for i in df.columns],
editable=True,
filter_action=“native”,
sort_action=‘native’,
sort_mode=‘multi’,
row_selectable=‘multi’,
row_deletable=True,
selected_rows=,
page_action=‘native’,
page_current=0,
page_size=10,
style_header={‘backgroundColor’: ‘rgb(30, 30, 30)’},
style_cell={
‘backgroundColor’: ‘rgb(150, 150, 100)’,
‘color’: ‘white’
},
),

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

@app.callback(Output(‘OM_NAME’, ‘options’),
[Input(‘upload-data’,‘contents’),
Input(‘upload-data’,‘filename’)
])
def parse_uploads(contents,filename):
if contents is not None:
contents = contents[0]
filename = filename[0]
df = parse_data(contents,filename)
columns = df.columns
if df is not None:
return [{‘label’: x, ‘value’: x} for x in columns]
else:
return
else:
return
return [{‘label’: i, ‘value’: i} for i in df.columns]

graph

@app.callback(Output(‘Graph’,‘figure’),
[
Input(‘upload-data’, ‘contents’),
Input(‘SUBMIT’,‘n_clicks’)
],
[
State(‘upload-data’, ‘filename’),
State(‘OM_NAME’,‘value’)
]
)
def update_graph(contents, filename,clicks,kpi):
traces =
if contents is not None:
contents = contents[0]
filename = filename[0]
df = parse_data(contents,filename)
columns = df.columns
for i in columns:
traces.append({‘x’: df[‘DateTime’], ‘y’: df[kpi], ‘name’: i})

figure = {
        'data': traces,
        'layout': {'title':kpi}
    }
return figure

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

Thanks for the reply. I am able to fix this issue by correcting data points. My earlier shared code was incorrect

With Regards
Araballi