使用Dash和Plotly实时更新表格数值

3
我将尝试使用Python构建一个仪表盘应用程序,模拟Q学习问题。在实施算法之前,我只关注使表格起作用,随机增加值,并在每次增加之间等待1秒钟。 这里的Q是一个pandas数据帧:
table = ff.create_table(Q,  height_constant=20)
table.layout.width=300

def update_Q(Q):
    for i in range(len(Q)):
        for j in range(1, len(Q.columns)):        
            Q.iloc[i,j] += np.random.choice([0,1,2])
    print(Q)
    return Q

我能够使用那个打印语句使它工作,在控制台上表格的值确实被更新了。然而在浏览器中,它只会在第一次更新,之后就保持不变了。以下是代码:
# Browser visualization

app.layout = html.Div([
        html.H1(children='Frozen Lake: Q-Learning Demo'),
        dcc.Graph(id='table', figure=table),
        dcc.Interval(
            id='time',
            interval=1*1000, # in milliseconds
            n_intervals=0)
        ]
    )


@app.callback(Output(component_id = 'table', component_property='figure'),
              [Input(component_id = 'time', component_property='n_intervals')])    
def update_table(n):   
    # Update values
    new_table = ff.create_table(update_Q(Q))
    time.sleep(1)
    return new_table


if __name__ == '__main__':
    app.run_server()

我错过了什么?


我建议你将你的解决方案复制到答案中。回答自己的问题没关系,甚至还有一个徽章 :) - Shovalt
谢谢你的提示! :) - Pablo Ruiz Ruiz
1个回答

3

问题已解决。 没有什么比早上喝咖啡更好的了;)

最好将表格的创建封装到一个函数中,并在每个间隔更新时调用它。此外,先前的语法不会保留第一个创建的表格中定义的样式。

    # Helper functions to draw and update values of the table
    def draw_Table(Q):
        table = ff.create_table(Q, index=True, height_constant=20)
        table.layout.width=300
        return table
    def update_Q(Q):
        for i in range(len(Q)):
            for j in range(1, len(Q.columns)):        
                Q.iloc[i,j] += np.random.choice([0,1,2])
        return Q

那么,

    @app.callback(Output(component_id = 'table', component_property='figure'),
                  [Input(component_id = 'time', component_property='n_intervals')])    
    def update_table(n):   
        # Update values
        new_table = draw_Table(update_Q(Q))
        time.sleep(1)
        return new_table

希望能对某些人有所帮助!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接