I’m new to Dash and trying to create a dashboard with upload data function and graph update with callbacks. However I got this error of “Cannot read property ‘data’ of null” when loading the page even before uploading any data. After many hours I still could not figure it out. Did I write anything wrong or miss anything important?
Any help would be much appreciated!
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.graph_objs as go
import pandas as pd
import base64
import io
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
colors = {
"graphBackground": "#F5F5F5",
"background": "#ffffff",
"text": "#000000"
}
app.layout = html.Div([
# adding a header and a paragraph
html.Div([
html.H1("Automatic Insight Generator"),
html.P("Project")
],
style = {'padding' : '25px' ,
'backgroundColor' : '#3aaab2'}),
# adding a upload object
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'
}
)
], style={'width':'100%','display': 'flex','align-items':'center','justify-content':'center'}
),
# adding a graph object
dcc.Graph(id='mygraph'),
# adding an insight object
html.Div([
html.Pre(
id='insight',
children='Insights from data:'
)
],
style={
'fontSize':20,
'color':'blue'
}
)
])
def process_content(contents):
type,data = contents.split(',')
decoded = base64.b64decode(data)
df = pd.read_csv(
io.StringIO(decoded.decode('utf-8')))
return df
@app.callback(
Output('mygraph','figure'),
[Input('upload_data','contents')]
)
def update_text(contents):
if contents is not None:
df = process_content(contents)
traces = []
for source_name in df['source'].unique():
df_by_source = df[df['source'] == source_name]
traces.append(go.Scatter(
x=df_by_source['month'],
y=df_by_source['net_sentiment'],
text=df_by_source['net_sentiment'],
mode='lines+markers',
opacity=0.7,
marker={'size': 15},
name=source_name
))
return {
'data': traces,
'layout': go.Layout(
xaxis={'title': 'Time of the Year'},
yaxis={'title': 'Net Sentiment Count'},
hovermode='closest',
plot_bgcolor=colors["graphBackground"],
paper_bgcolor=colors["graphBackground"]
)
}
if __name__ == '__main__':
app.run_server(debug=True)