从单点划线回调中输出图形和表格



我想通过短划线回调生成一个图和表,但代码会输出其中一个。

下面是代码的最后一部分。数据通过链式回调(两个下拉菜单-LGA和SMA(和单选按钮(标准偏差选择器(进行过滤。

有没有一种简单的方法来生成这两个输出,或者我需要添加另一个回调并定义其他函数?

html.Div(
id='graph-container', 
children=[]),

dash_table.DataTable(
id='table-container',
columns = [{"name": i, "id": i} for i in df],
data=df.to_dict('records'),
),
])

使用选项和值填充SMA的下拉列表

@app.callback(
Output('SMA-dpdn', 'options'),
Output('SMA-dpdn', 'value'),
Input('LGA-dpdn', 'value'),
)
def set_LGA_options(chosen_LGA):
dff = df[df.LGA==chosen_LGA]
SMAs_of_LGAs = [{'label': c, 'value': c} for c in sorted(dff.SMA.unique())]
values_selected = [x['value'] for x in  SMAs_of_LGAs]
return  SMAs_of_LGAs, values_selected
@app.callback(
Output('graph-container', 'children'),
Output('table-container', 'data'),
Input('radio_items', 'value'),   
Input('SMA-dpdn', 'value'), 
Input('LGA-dpdn', 'value'),
prevent_initial_call=True
)

创建图形/表格组件并填充

def graph(max_deviations, selected_SMA, selected_LGA):
if len(selected_SMA) == 0:
return dash.no_update
else: 
dff = df[(df.LGA==selected_LGA) & (df.SMA.isin(selected_SMA))]
data = pd.DataFrame(data=dff)
x = dff.TIME
y = dff.CHANGE
mean = np.mean(y)
standard_deviation = np.std(y)
distance_from_mean = abs(y - mean)
not_outlier = distance_from_mean < max_deviations * standard_deviation
no_outliers = y[not_outlier]
trim_outliers = pd.DataFrame(data=no_outliers)
dfd = pd.merge(trim_outliers, dff, left_index=True, right_index=True)
dfd['CHANGE'] = dfd['CHANGE_x']
fig = px.scatter(dfd, x='TIME', y='CHANGE', color ='SMA', trendline='ols', size='PV', height=500, width=800, hover_name='SMA')    

return dfd.to_dict('records')
return dcc.Graph(id='display-map', figure=fig)

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

您已经在回调中正确定义了两个输出,但您只返回了一个不正确的值。

下面的代码是您的示例,它演示了返回多个值的正确方法。我还切换了no_update逻辑,以演示一种更干净的代码结构方法,该方法可以降低返回时引入错误的风险:

@app.callback(
Output('graph-container', 'children'),
Output('table-container', 'data'),
Input('radio_items', 'value'),   
Input('SMA-dpdn', 'value'), 
Input('LGA-dpdn', 'value'),
prevent_initial_call=True
)
def graph(max_deviations, selected_SMA, selected_LGA):
if len(selected_SMA) > 0: 
# Do processing to create a dfd record and the figure for the Graph
return dcc.Graph(id='display-map', figure=fig), dfd.to_dict('records')
# No update if length was zero.
return dash.no_update, dash.no_update

最新更新