简体   繁体   English

使用Dash和Plotly更新表值

[英]Updating table values live with Dash and Plotly

I am trying to build a dash app in Python to simulate a Q-Learning problem. 我正在尝试在Python中构建一个破折号应用程序来模拟Q-Learning问题。 Before implementing the algorithm I am just focusing on making the table work incrementing randomly the values and waiting 1 sec between each increment. 在实现算法之前,我只是专注于使表工作随机递增值并在每个增量之间等待1秒。

Q is a pandas dataframe here: Q是一个熊猫数据帧:

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

I am able to make it work with that print statement, the value of the table on the console is indeed getting updated. 我能够使用print语句,控制台上表的值确实得到了更新。

However, in the browser it just get updated the first time, but then it remains static. 但是,在浏览器中它只是第一次更新,但它仍然是静态的。 Here is the code: 这是代码:

# 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()

What am I missing? 我错过了什么?

SOLVED. 解决了。 Nothing like a morning caffee ; 没有像早晨的咖啡; )

It is better to wrap the creation of the table into a function and call it for every update at every interval. 最好将表的创建包装到一个函数中,并在每个时间间隔为每次更新调用它。 Furthermore, previous syntax won't keep style defined in the first table created. 此外,以前的语法不会在创建的第一个表中定义样式。

    # 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

And then, 接着,

    @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

Hope it helps someone! 希望它可以帮到某人!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM