【问题标题】:Is there a way to constantly update a graph figure while a switch is on in Dash Plotly Python?有没有办法在 Dash Plotly Python 中打开开关时不断更新图形?
【发布时间】:2022-01-03 04:25:35
【问题描述】:

我有一个使用算法更新图形图形的函数,以及一个用于返回图形图形的回调函数(以及许多其他内容)。这是基本思想:

for i in range(0,5):
    time.sleep(0.1)
    randomfunction(i)
    return plot

如何在不中断循环的情况下更新图表?我尝试使用 yield 而不是 return 无济于事,因为回调不希望输出生成器类。

【问题讨论】:

    标签: python plotly plotly-dash plotly-python


    【解决方案1】:

    虽然公认的答案确实有效,但对于任何想要在没有外部存储的情况下执行此操作的人来说,还有另一种方法。

    有一个名为dcc.Interval 的 Dash 核心组件,您可以使用它来不断触发回调,您可以在其中更新图表。

    例如,设置一个包含图表布局的布局和以下内容:

    import dash_core_components as dcc
    dcc.Interval(id="refresh-graph-interval", disabled=False, interval=1000)
    

    然后,在您的回调中:

    from dash.exceptions import PreventUpdate
    
    @app.callback(
        Output("graph", "figure"), 
        [Input("refresh-graph-interval", "n_intervals")]
    )
    def refresh_graph_interval_callback(n_intervals):
        if n_intervals is not None:
            for i in range(0,5):
                time.sleep(0.1)
                randomfunction(i)
                return plot
        raise PreventUpdate()
    

    【讨论】:

    • 谢谢,这真的很有帮助。不过,我所做的是将 for 循环替换为函数的参数为​​ (n_intervals%5),因为它对我的特定任务(和拥挤的回调)效果更好。
    【解决方案2】:

    Dash 中的标准方法是将图形(或仅数据)从循环中写入服务器端缓存(例如磁盘上的文件或 Redis 缓存),

    for i in range(0,5):
        time.sleep(0.1)
        randomfunction(i)
        # write data to server side cache
    

    然后使用Interval 组件触发从缓存读取并更新图形的回调。类似的,

    @app.callback(Output("graph_id", "figure"), Input("interval_id", "n_intervals")):
    def update_graph(_):
        data = ... # read data from server side cache
        figure = ...  # generate figure from data
        return figure
    

    【讨论】:

      猜你喜欢
      • 2021-11-26
      • 2019-01-30
      • 2020-05-21
      • 2019-09-05
      • 1970-01-01
      • 2019-01-06
      • 1970-01-01
      • 1970-01-01
      • 2022-01-20
      相关资源
      最近更新 更多