更新 Dash 中多个绘图的绘图

Update plots for multiple plots in Dash

我有一个非常基本的问题,主要是为了了解 Dash 在变量更改时如何处理图形更新过程。我刚刚开始构建仪表板,但我仍然不熟悉完整的语法。

我的布局中有一个绘图、一个下拉框、回调和更新函数,如下所示:

@app.callback(
    Output(component_id='plot1', component_property='figure'),
    Input(component_id='drop1', component_property='value')
)
def update_graph(sel):
    """ Stuff for updating the plot """
    return fig

效果很好,但我不完全理解“为什么”。

现在,我的问题是...

  1. 回调如何知道 update_graph() 是为了更新该图而调用的函数?它从未在回调方法中被调用,下拉选择的值从未真正传递到任何地方,等等。
  2. 如果我有多个动态图会怎样?我的布局中的另一个下拉框或任何其他反应元素,我想根据第二个输入对象更新第二个图形。我必须进行另一个回调和另一个更新功能吗?同样,每个回调如何知道要使用哪个更新函数?

提前致谢!

好的,我将用一张图来解释 plotly 文档中的一个简单示例。一旦我们理解了单个图,那么多个图就变得更容易理解了。

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

app.layout = html.Div([
    html.H6("Change the value in the text box to see callbacks in action!"),
    html.Div(["Input: ",
              dcc.Input(id='my-input', value='initial value', type='text')]),
    html.Br(),
    html.Div(id='my-output'),

])


@app.callback(
    Output(component_id='my-output', component_property='children'),
    Input(component_id='my-input', component_property='value')
)
def update_output_div(input_value):
    return 'Output: {}'.format(input_value)


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

所以开始让我们注意输入和输出 component_id。请注意,输入的 component_iddcc.Input id 匹配。匹配的id意味着在装饰器、@app.callback和布局对象之间有一个link。这个 link 意味着一旦输入发生变化,装饰器就会被调用,装饰器将查看其各自的输出 id。然后装饰器将寻求更新输出组件,即 HTML div。为了做到这一点,装饰器将始终查看其正下方的函数,在本例中为 update_output_div。更改(输入)的值将传递给此函数。

好的,现在看多张图。在下面的代码中,我将省略 app.layout 声明,假设下面的每个 id(正方形、立方体、三体、x^x、num-multi、dropdown)都是 linked给他们的同行。

@app.callback(
    Output('square', 'children'),
    Output('cube', 'children'),
    Output('twos', 'children'),
    Output('threes', 'children'),
    Output('x^x', 'children'),
    Input('num-multi', 'value'),
    Input('dropdown', 'value2'))

def callback_a(v, v2):
   # update 

同样,装饰器将只查找任何输入的变化,然后通过 callback_a 函数

更新每个输出

所以回答你的第一个问题。回调将始终直接调用其自身下方的函数,而无需您隐式编码。您当然可以决定在该函数内调用更多函数。例如,如果我有多个可能不相关的输入,我可以查找实际触发的内容。

@app.callback(
    Output('map', 'figure'),
    Input('map','clickData'),
    Input('map','selectedData'))
def update_scatter_plots(
    ctx = dash.callback_context
    if ctx.triggered[0]['prop_id'] == 'map.clickData':
       #it was a click 
    elif ctx.triggered[0]['prop_id'] == 'map.selectedData':
       #it was a selection

这里我有一个地图图表,我有两个不同的输入,一个点击事件和一个 select 事件,根据上下文,我可以决定如何处理传递的信息。

关于你的第二个问题,如果你想让我详细说明一下,请告诉我。