好的,我将仅用一张图表来解释 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_id 与 dcc.Input id 匹配。匹配的 id 表示装饰器 @app.callback 和布局对象之间存在链接。这个链接意味着一旦输入发生变化,装饰器将被调用,装饰器将查看其各自的输出 id。然后装饰器将寻求更新作为 HTML div 的输出组件。为了做到这一点,装饰器将始终查看其正下方的函数,在本例中为update_output_div。更改的值(输入)将传递给此函数。
好的,现在进入多个图表。在下面的代码中,我将省略 app.layout 声明,只是假设下面的每个 id(square、cube twos、threes、x^x、num-multi、dropdown)都链接到它们的对应项。
@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
这里我有一个地图,我有两个不同的输入,一个点击事件和一个选择事件,根据上下文,我可以决定如何处理传递的信息。
至于您的第二个问题,如果您希望我详细说明,请告诉我。