文本框中的输入更改时重新加载图形

Reload Graph When Input in Textbox Changes

我现在遇到的情况是,每当文本框中的输入发生变化时,我都无法让我的图表发生变化。我还想确保无论何时对文本框进行更改,它都会反映到我想要的 DB [图表] 输出,并且应该连续完成,即图表将连续流动。

然而,在尝试使用按钮启动 n 间隔后,我仍然没有这样做。

如果有人能看看我的代码就太好了。太感谢了。

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
import time


external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

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

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

    ]
)

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


def update_graph_scatter(sentiment_term):
    try:
        conn = sqlite3.connect('twitter.db')
        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)/2)).mean()

        df['date'] = pd.to_datetime(df['unix'],unit='ms')
        df.set_index('date', inplace=True)

        df = df.resample('0.15min').mean()
        df.dropna(inplace=True)
        X = df.index
        Y = df.sentiment_smoothed

        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)

您的回调函数 update_graph_scatter 缺少第二个参数。您可以将其更改为:

def update_graph_scatter(sentiment_term, n_intervals):

你的回调装饰器也应该是:

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

因为它有一个额外的“[”破坏它。

我不确定这是否是您遇到问题的原因,但有可能。我希望我有 50 个声望 post 这只是一个评论,因为它的贡献很小。