Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot read properly 'data ' of null (DASH)

When I run the below code it loads the web, but then it leaves an error message, it is because in some section there is no data, can a conditional help?

issue

I uploaded the code but I do not know where to act, i am new on Dash and my knowledge in javascript is limited.

My main file

import dash
from dash.dependencies import Output, Input
import dash_core_components as dcc
import dash_html_components as html
import plotly
import random
import plotly.graph_objs as go
from collections import deque
import sqlite3
import pandas as pd

#popular topics: google, olympics, trump, gun, usa

app = dash.Dash(__name__)
app.layout = html.Div(
    [   html.H2('Live Twitter Sentiment'),
        dcc.Input(id='sentiment_term', value='trump', type='text'),
        dcc.Graph(id='live-graph', animate=False),
        dcc.Interval(
            id='graph-update',
            interval=1*1000
        ),
    ]
)


@app.callback(Output('live-graph', 'figure'),
                   [Input(component_id='sentiment_term', component_property='value')])


def update_graph_scatter(sentiment_term):
    try:
        conn = sqlite3.connect('twitter.db')
        c = conn.cursor()
        df = pd.read_sql("SELECT * FROM sentiment WHERE tweet LIKE ? ORDER BY unix DESC LIMIT 1000", conn, params=('%' + sentiment_term + '%',))
        df.sort_values('unix', inplace=True)
        df['sentiment_smoothed'] = df['sentiment'].rolling(int(len(df)/5)).mean()
        df.dropna(inplace=True)

        X = df.unix.values[-100:]
        Y = df.sentiment_smoothed.values[-100:]

        data = plotly.graph_objs.Scatter(
                x=X,
                y=Y,
                name='Scatter',
                mode= 'lines+markers'
                )

        return {'data': [data],'layout' : go.Layout(xaxis=dict(range=[min(X),max(X)]),
                                                    yaxis=dict(range=[min(Y),max(Y)]),
                                                    title='Term: {}'.format(sentiment_term))}

    except Exception as e:
        with open('errors.txt','a') as f:
            f.write(str(e))
            f.write('\n')


if __name__ == '__main__':
    app.run_server(debug=True)
like image 342
Lorenzo Castagno Avatar asked Mar 02 '23 09:03

Lorenzo Castagno


1 Answers

Sometimes Dash can struggle if the prop being updated by a callback hasn't been initialized. In this case, the figure prop of the dcc.Graph was never declared. Setting an explicit empty value, such as figure={} is often enough to resolve this sort of error.

like image 163
coralvanda Avatar answered Mar 05 '23 15:03

coralvanda