情节:带有实时图表的破折号按钮不起作用

Plotly: Dash button with live graph not working

我开发了 python 基于 dash 的监控应用程序。作为项目的一部分,我想显示实时图表并根据用户输入更改实时图表值。我被困在这部分。当我开始在输入框(例如:temp)中输入时,实时图表得到更新图表不断更新每个字母,如 t、te、tem、temp。所以我创建了一个按钮来提交输入值。图表仍在为每个字母更新。

相同的代码:

app = dash.Dash(__name__)
app.layout = html.Div(
    [ 
    dcc.Input(id='input-value', value='example', type='text'),
    html.Button('Submit', id="submit-button"),
    dcc.Graph(id='live-graph', animate=False),
    dcc.Interval(
        id='graph-update',
        interval=1*1000
    ),
]
)

回调函数如下

@app.callback(Output('live-graph', 'figure'),
          [Input('submit-button','n_clicks')],
          state=[State(component_id='sentiment_term', component_property='value')],
          events=[Event('graph-update', 'interval')])

def update_graph_scatter(n_clicks, input_value):
    conn = sqlite3.connect('database.db')
    c = conn.cursor()
    df = pd.read_sql("SELECT * FROM table WHERE colume LIKE ? ORDER BY unix DESC LIMIT 1000", conn ,params=('%' + input_value+ '%',))
    df.sort_values('unix', inplace=True)

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

    X = df.index
    Y = df.column

    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)])}

注意:如果我删除了按钮开始的时间间隔 working.but 我想实时更新以及按钮

你确定每个字母的更新都是因为输入?听起来间隔使用您输入的未完成输入更新图表。

P.S.: 我猜你的输入和状态 ID 之间存在名称差异。

您可以使用像 div 这样的中间组件来保存文本字段的输入并仅在单击按钮时更新 div。 所以你会

app = dash.Dash(__name__)
app.layout = html.Div([ 
    dcc.Input(id='input-value', value='example', type='text'),
    html.Div(['example'], id='input-div', style={'display': 'none'}),
    html.Button('Submit', id="submit-button"),
    dcc.Graph(id='live-graph', animate=False),
    dcc.Interval(
        id='graph-update',
        interval=1*1000
    ),
])

现在您仅在单击按钮时更新 div:

@app.callback(Output('input-div', 'children'),
              [Input('submit-button', 'n_clicks')],
              state=[State(component_id='input-value', component_property='value')])
def update_div(n_clicks, input_value):
    return input_value

并且图表始终使用 div 内容来查询您的数据库(在间隔触发或 div 更改时):

@app.callback(Output('live-graph', 'figure'),
              [Input('graph-update', 'interval'),
               Input('input-div', 'children')])
def update_graph_scatter(n, input_value):
    ...