简体   繁体   English

有没有办法在 Dash Plotly Python 中的开关打开时不断更新图形?

[英]Is there a way to constantly update a graph figure while a switch is on in Dash Plotly Python?

I have a function that updates the figure of a graph using an algorithm, and a callback function to return the graph's figure (among many other things).我有一个 function 使用算法更新图形的图形,以及一个回调 function 以返回图形的图形(以及许多其他内容)。 This is the basic idea:这是基本思想:

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

How can I update the graph without breaking the loop?如何在不中断循环的情况下更新图表? I've tried using yield instead of return to no avail as the callback does not expect a generator class to be output.我尝试使用 yield 而不是 return 无济于事,因为回调不希望生成器 class 是 output。

The standard approach in Dash would be to write the figure (or just the data) to a server side cache (eg a file on disk or a Redis cache) from within the loop, Dash 中的标准方法是从循环中将图形(或仅数据)写入服务器端缓存(例如磁盘上的文件或 Redis 缓存),

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

and then use an Interval component to trigger a callback that reads from the cache and updates the graph.然后使用Interval组件触发从缓存读取并更新图形的回调。 Something like,就像是,

@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

While the accepted answer certainly works, there is another way to do it for anyone who may want to do this without external storage.虽然公认的答案肯定有效,但对于任何想要在没有外部存储的情况下执行此操作的人来说,还有另一种方法可以做到这一点。

There is a Dash Core Component called dcc.Interval that you can use to constantly trigger a callback, within which you can update your graph.有一个名为dcc.Interval的 Dash 核心组件,您可以使用它来不断触发回调,您可以在其中更新图表。

For example, set up a layout that has your graph's layout and the following:例如,设置具有图形布局的布局和以下内容:

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

Then, in your callback:然后,在您的回调中:

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

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

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